/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.service.table.impl;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.je.common.base.DynaBean;
import com.je.common.base.constants.ConstantVars;
import com.je.common.base.constants.table.ColumnEnum;
import com.je.common.base.constants.table.ColumnType;
import com.je.common.base.constants.table.TableType;
import com.je.common.base.constants.tree.NodeType;
import com.je.common.base.db.JEDatabase;
import com.je.common.base.entity.extjs.DbModel;
import com.je.common.base.exception.APIWarnException;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;
import com.je.common.base.mapper.query.NativeQuery;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaRbacService;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.QueryBuilderService;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.service.rpc.CommonTableRpcService;
import com.je.common.base.table.BuildingSqlFactory;
import com.je.common.base.table.ParseBuildingSqlFactory;
import com.je.common.base.table.service.PCDataService;
import com.je.common.base.util.*;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.cache.table.DynaCache;
import com.je.meta.cache.table.TableCache;
import com.je.meta.model.view.ViewColumn;
import com.je.meta.model.view.ViewDdlVo;
import com.je.meta.model.view.ViewOuput;
import com.je.meta.rpc.framework.product.ProductRpcService;
import com.je.meta.service.common.MetaBeanService;
import com.je.meta.service.common.MetaDevelopLogService;
import com.je.meta.service.func.MetaFuncInfoService;
import com.je.meta.service.table.*;
import com.je.meta.service.table.key.ChangePrimaryKeyService;
import com.je.rbac.rpc.MenuRpcService;
import com.je.rbac.rpc.PermissionRpcService;
import com.je.servicecomb.RpcSchemaFactory;
import com.je.table.vo.TableDataView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.SQLSyntaxErrorException;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;
import static com.je.servicecomb.JECloud.PRODUCT_CORE_META;

@Service
public class MetaTableServiceImpl implements MetaTableService {

    private static final Logger logger = LoggerFactory.getLogger(MetaTableServiceImpl.class);

    @Autowired
    private MetaService metaService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private MetaDevelopLogService developLogService;
    @Autowired
    private MetaBeanService metaBeanService;
    @Autowired
    private PCDataService pcDataService;
    @Autowired
    private TableCache tableCache;
    @Autowired
    private DynaCache dynaCache;
    @Autowired
    private MetaTableTraceService metaTableTraceService;
    @Autowired
    private MetaTableColumnService metaTableColumnService;
    @Autowired
    private MetaTableKeyService metaTableKeyService;
    @Autowired
    private MetaTableIndexService metaTableIndexService;
    @Autowired
    private MetaRbacService metaRbacService;
    @Autowired
    private Environment environment;
    @Autowired
    private ProductRpcService productRpcService;
    @Autowired
    private MetaViewService mateViewService;
    @Autowired
    private MetaTableService tableService;
    @Autowired
    protected MetaFuncInfoService funcInfoService;
    @Autowired
    private PermissionRpcService permissionRpcService;

    @Autowired
    private ChangePrimaryKeyService changePrimaryKeyService;

    @Autowired
    private MetaResColumnService resColumnService;

    @Autowired
    private QueryBuilderService queryBuilderService;

    @Autowired
    private MenuRpcService menuRpcService;

    /**
     * 在上面
     */
    private static final String ABOVE = "above";
    /**
     * 在下面
     */
    private static final String BELOW = "below";
    /**
     * 在里面
     */
    private static final String INSIDE = "inside";


    @Override
    @Transactional
    public boolean createTable(String resourceTableId) {
        boolean success = true;
        String result = checkTableForApply(resourceTableId);
        if(StringUtil.isNotEmpty(result)){
            throw new PlatformException(result, PlatformExceptionEnum.UNKOWN_ERROR);
        }
        List<String> arraySql = generateCreateDDL(resourceTableId);
        for (String sql : arraySql) {
            if (StringUtil.isNotEmpty(sql)) {
                metaService.executeSql(sql);
            }
        }
        afterTableCreated(resourceTableId);
        DynaBean table = metaService.selectOneByPk("JE_CORE_RESOURCETABLE",resourceTableId);
        developLogService.doDevelopLog("applyTable","应用资源表","table","资源表",table.getStr("RESOURCETABLE_TABLENAME"), table.getStr("RESOURCETABLE_TABLECODE"),table.getStr("JE_CORE_RESOURCETABLE_ID"),table.getStr("SY_PRODUCT_ID"));
        return success;
    }

    @Override
    @Transactional
    public List<String> generateUpdateDDL(String resourceTableId, List<DbModel> dbModels) {
        DynaBean resourceTable = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", resourceTableId);

        List<DynaBean> columns = metaService.select(ConditionsWrapper.builder().table("JE_CORE_TABLECOLUMN")
                .apply("TABLECOLUMN_RESOURCETABLE_ID={0} ORDER BY TABLECOLUMN_CLASSIFY ASC,SY_ORDERINDEX ASC", resourceTable.getStr("JE_CORE_RESOURCETABLE_ID")));

        List<DynaBean> keys = metaService.select(ConditionsWrapper.builder().table("JE_CORE_TABLEKEY")
                .eq("TABLEKEY_RESOURCETABLE_ID", resourceTable.getStr("JE_CORE_RESOURCETABLE_ID")));

        List<DynaBean> indexs = metaService.select("JE_CORE_TABLEINDEX",
                ConditionsWrapper.builder().eq("TABLEINDEX_RESOURCETABLE_ID", resourceTable.getStr("JE_CORE_RESOURCETABLE_ID")));

        resourceTable.set(BeanService.KEY_TABLE_COLUMNS, columns);
        resourceTable.set(BeanService.KEY_TABLE_KEYS, keys);
        resourceTable.set(BeanService.KEY_TABLE_INDEXS, indexs);
        //获取clob字段
        List<String> arraySql = BuildingSqlFactory.build().getDDL4UpdateTable(resourceTable, dbModels);
        return arraySql;
    }

    @Override
    @Transactional
    public void afterTableUpdated(String resourceTableId) {
        DynaBean resourceTable = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", resourceTableId);
        String tableCode = resourceTable.getStr("RESOURCETABLE_TABLECODE");

        List<DynaBean> columns = metaService.select(ConditionsWrapper.builder().table("JE_CORE_TABLECOLUMN")
                .apply("TABLECOLUMN_RESOURCETABLE_ID={0} ORDER BY TABLECOLUMN_CLASSIFY ASC,SY_ORDERINDEX ASC", resourceTable.getStr("JE_CORE_RESOURCETABLE_ID")));

        List<DynaBean> keys = metaService.select(ConditionsWrapper.builder().table("JE_CORE_TABLEKEY")
                .eq("TABLEKEY_RESOURCETABLE_ID", resourceTable.getStr("JE_CORE_RESOURCETABLE_ID")));

        List<DynaBean> indexs = metaService.select("JE_CORE_TABLEINDEX", ConditionsWrapper.builder().eq("TABLEINDEX_RESOURCETABLE_ID", resourceTable.getStr("JE_CORE_RESOURCETABLE_ID")));

        //把字段和键的标示符改掉
        //声明已创建的索引
        Set<String> indexCodes = new HashSet<String>();
        for (DynaBean column : columns) {
            if ("0".equals(column.getStr("TABLECOLUMN_ISCREATE"))) {
                metaTableTraceService.saveTableTrace("JE_CORE_TABLECOLUMN", null, column, "INSERT", resourceTable.getStr("JE_CORE_RESOURCETABLE_ID"), "1");
            }
        }
        for (DynaBean index : indexs) {
            indexCodes.add(index.getStr("TABLEINDEX_FIELDCODE"));
            if ("0".equals(index.getStr("TABLEINDEX_ISCREATE"))) {
                metaTableTraceService.saveTableTrace("JE_CORE_TABLEINDEX", null, index, "INSERT", resourceTable.getStr("JE_CORE_RESOURCETABLE_ID"), "1");
            }
        }
        for (DynaBean key : keys) {
            if ("0".equals(key.getStr("TABLEKEY_ISCREATE"))) {
                metaTableTraceService.saveTableTrace("JE_CORE_TABLEKEY", null, key, "INSERT", resourceTable.getStr("JE_CORE_RESOURCETABLE_ID"), "1");
            }
        }
        /**---------------------------功能中增加字段开始-----------------------------------------*/
        List<DynaBean> funcs = metaService.select("JE_CORE_FUNCINFO",
                ConditionsWrapper.builder().eq("FUNCINFO_TABLENAME", resourceTable.getStr("RESOURCETABLE_TABLECODE")));
        for (DynaBean fun : funcs) {
            //列表字段数量
            long columnCount = 0;
            //表单字段数量
            long fieldCount = 0;
            String funId = fun.getStr("JE_CORE_FUNCINFO_ID");
            String columnSql = "select RESOURCECOLUMN_CODE,SY_ORDERINDEX from JE_CORE_RESOURCECOLUMN where RESOURCECOLUMN_FUNCINFO_ID ={0} and RESOURCECOLUMN_IFIMPL = '1' ORDER BY SY_ORDERINDEX DESC";
            List<Map<String, Object>> mapList = metaService.selectSql(columnSql, funId);
            columnCount = Long.parseLong(StringUtil.isEmpty(mapList.get(0).get("SY_ORDERINDEX"))?"0":mapList.get(0).get("SY_ORDERINDEX").toString());
            List<String> columnList = mapList.stream().map(p -> p.get("RESOURCECOLUMN_CODE").toString()).collect(Collectors.toList());

            String fieldSql = "select RESOURCEFIELD_CODE,SY_ORDERINDEX from JE_CORE_RESOURCEFIELD where RESOURCEFIELD_FUNCINFO_ID = {0} and RESOURCEFIELD_IFIMPL = '1' ORDER BY SY_ORDERINDEX DESC ";
            mapList = metaService.selectSql(fieldSql, funId);
            fieldCount = Long.parseLong(StringUtil.isEmpty(mapList.get(0).get("SY_ORDERINDEX"))?"0":mapList.get(0).get("SY_ORDERINDEX").toString());
            List<String> fieldList = mapList.stream().map(p -> p.get("RESOURCEFIELD_CODE").toString()).collect(Collectors.toList());

            mapList = metaService.selectSql("select max(SY_ORDERINDEX) as ORDERINDEX from JE_CORE_RESOURCECOLUMN where RESOURCECOLUMN_FUNCINFO_ID ={0} and RESOURCECOLUMN_IFIMPL = '1'", funId);
            List<Object> maxOrder = mapList.stream().map(p -> p.get("ORDERINDEX").toString()).collect(Collectors.toList());

            mapList = metaService.selectSql("select max(SY_ORDERINDEX) as ORDERINDEX from JE_CORE_RESOURCEFIELD where RESOURCEFIELD_FUNCINFO_ID = {0} and RESOURCEFIELD_IFIMPL = '1'", funId);
            List<Object> fieldMaxOrder = mapList.stream().map(p -> p.get("ORDERINDEX").toString()).collect(Collectors.toList());

            Integer fieldOrderIndex = 0;
            Integer columnOrderIndex = 0;
            if (maxOrder != null && maxOrder.size() > 0) {
                Object orderObj = maxOrder.iterator().next();
                if (orderObj == null) {
                    orderObj = 0;
                }
                columnOrderIndex = Integer.parseInt(orderObj.toString());
            }
            if (fieldMaxOrder != null && fieldMaxOrder.size() > 0) {
                Object orderObj = fieldMaxOrder.iterator().next();
                if (orderObj == null) {
                    orderObj = 0;
                }
                fieldOrderIndex = Integer.parseInt(orderObj.toString());
            }
            String nowDate = DateUtils.formatDateTime(new Date());
            for (int i = 0; i < columns.size(); i++) {
                DynaBean column = columns.get(i);
                if ("SY__POSTIL".equals(column.getStr("TABLECOLUMN_CODE")) || "SY__MARK".equals(column.getStr("TABLECOLUMN_CODE"))) {
                    continue;
                }
                if (!columnList.contains(column.getStr("TABLECOLUMN_CODE"))) {
                    Boolean isUpdate = false;
                    if (columnList.contains(column.getStr("TABLECOLUMN_OLDCODE"))) {
                        isUpdate = true;
                    }
                    if (!isUpdate) {
                        /*for(Map<String,Object> map:columnlistPlan){*/
                            DynaBean rc = new DynaBean("JE_CORE_RESOURCECOLUMN", false);
                            rc.set(BeanService.KEY_PK_CODE, "JE_CORE_RESOURCECOLUMN_ID");
                            //rc.setStr("RESOURCECOLUMN_PLAN_ID",map.get("JE_CORE_RESOURCECOLUMN_PLAN_ID").toString());
                            rc.set("RESOURCECOLUMN_FUNCINFO_ID", fun.getStr("JE_CORE_FUNCINFO_ID"));
                            rc.set("RESOURCECOLUMN_CODE", column.get("TABLECOLUMN_CODE"));
                            rc.set("RESOURCECOLUMN_BULKING_TYPE", "1");
                            rc.set("RESOURCECOLUMN_NAME", column.get("TABLECOLUMN_NAME"));
                            //将导入的字段标识为true
                            rc.set("RESOURCECOLUMN_IFIMPL", "1");
                            //是否快速查询 false
                            rc.set("RESOURCECOLUMN_QUICKQUERY", "0");
                            //rc.set("SY_ORDERINDEX", columnOrderIndex + i + 1);
                            rc.set("SY_ORDERINDEX", 0);
                            //设置默认宽度为100
                            rc.set("RESOURCECOLUMN_WIDTH", "100");
                            //设置默认宽度为80
                            rc.set("RESOURCECOLUMN_WIDTH_EN", "");
                            //是否拥有转换器conversion
                            rc.set("RESOURCECOLUMN_CONVERSION", "0");
                            //是否拥有转换器highlighting
                            rc.set("RESOURCECOLUMN_HIGHLIGHTING", "0");
                            //是否超链接hyperLink
                            rc.set("RESOURCECOLUMN_HYPERLINK", "0");
                            //是否在字典中取
                            rc.set("RESOURCECOLUMN_ISDD", "0");
                            //合并单元格      否
                            rc.set("RESOURCECOLUMN_MERGE", "0");
                            //锁定列  否
                            rc.set("RESOURCECOLUMN_LOCKED", "");
                            //多表头   否
                            rc.set("RESOURCECOLUMN_MORECOLUMN", "0");
                            rc.set("RESOURCECOLUMN_ISPK", "0");
                            //启用图标
                            rc.set("RESOURCECOLUMN_ENABLEICON", "0");
                            rc.set("RESOURCECOLUMN_SYSMODE", fun.getStr("FUNCINFO_SYSMODE"));
                            //是否可以为空  true
                            rc.set("RESOURCECOLUMN_ALLOWBLANK", "1");
                            rc.set("RESOURCECOLUMN_QUERYTYPE", "no");
                            //字段类型  默认为无  不可编辑
                            rc.set("RESOURCECOLUMN_XTYPE", "uxcolumn");
                            //列表编辑   默认为否
                            rc.set("RESOURCECOLUMN_ALLOWEDIT", "0");
                            rc.set("RESOURCECOLUMN_HIDDEN", "1");
                            rc.set("RESOURCECOLUMN_ALIGN", "left");
                            rc.set("RESOURCECOLUMN_ALIGN_TITLE", "left");
                            if ("SY_ACKFLAG".equals(rc.getStr("RESOURCECOLUMN_CODE"))) {
                                rc.set("RESOURCECOLUMN_LAZYLOAD", "1");
                                columnCount = columnCount+1;
                                rc.set("SY_ORDERINDEX", columnCount);
                            }
                            if ("SY_ACKUSERNAME".equals(rc.getStr("RESOURCECOLUMN_CODE"))) {
                                columnCount = columnCount+1;
                                rc.set("SY_ORDERINDEX", columnCount);
                            }
                            if ("SY_ACKUSERID".equals(rc.getStr("RESOURCECOLUMN_CODE"))) {
                                columnCount = columnCount+1;
                                rc.set("SY_ORDERINDEX", columnCount);
                            }
                            if ("SY_ACKTIME".equals(rc.getStr("RESOURCECOLUMN_CODE"))) {
                                columnCount = columnCount+1;
                                rc.set("SY_ORDERINDEX", columnCount);
                            }

                            if ("SY_FUNCEDIT".equals(rc.getStr("RESOURCECOLUMN_CODE"))) {
                                rc.set("RESOURCECOLUMN_LAZYLOAD", "1");
                            }
                            if (indexCodes.contains(column.get("TABLECOLUMN_CODE"))) {
                                rc.set("RESOURCECOLUMN_INDEX", "1");
                                rc.set("RESOURCECOLUMN_ORDER", "0");
                            } else {
                                rc.set("RESOURCECOLUMN_INDEX", "0");
                                rc.set("RESOURCECOLUMN_ORDER", "0");
                            }
                            rc.set("SY_CREATETIME", nowDate);
                            rc.set("SY_CREATEUSERID", SecurityUserHolder.getCurrentAccountRealUserId());
                            rc.set("SY_CREATEUSERNAME", SecurityUserHolder.getCurrentAccountRealUserName());
                            rc.set("SY_CREATEORGID", SecurityUserHolder.getCurrentAccountRealOrgId());
                            rc.set("SY_CREATEORGNAME", SecurityUserHolder.getCurrentAccountRealOrgName());
                            rc.set("RESOURCECOLUMN_DESCRIPTION", column.getStr("TABLECOLUMN_REMARK"));
                            metaService.insert(rc);
                       /* }*/

                    } else {
                        //如果是修改列名的情况。 则修改功能中的column列编码
                        List<DynaBean> rclist = metaService.select("JE_CORE_RESOURCECOLUMN",
                                ConditionsWrapper.builder().eq("RESOURCECOLUMN_FUNCINFO_ID", fun.getStr("JE_CORE_FUNCINFO_ID"))
                                        .eq("RESOURCECOLUMN_CODE", column.get("TABLECOLUMN_OLDCODE")));
                        for(DynaBean rc:rclist){
                            rc.set(BeanService.KEY_TABLE_CODE, "JE_CORE_RESOURCECOLUMN");
                            rc.set("RESOURCECOLUMN_CODE", column.get("TABLECOLUMN_CODE"));
                            rc.set("RESOURCECOLUMN_NAME", column.get("TABLECOLUMN_NAME"));
                            rc.set("RESOURCECOLUMN_BULKING_TYPE", "2");
                            if (indexCodes.contains(column.get("TABLECOLUMN_CODE"))) {
                                rc.set("RESOURCECOLUMN_INDEX", "1");
                                rc.set("RESOURCECOLUMN_ORDER", "0");
                            } else {
                                rc.set("RESOURCECOLUMN_INDEX", "0");
                                rc.set("RESOURCECOLUMN_ORDER", "0");
                            }
                            metaService.update(rc);
                        }

                    }
                } else if (indexCodes.contains(column.get("TABLECOLUMN_CODE"))) {
                    List<DynaBean> rcList = metaService.select("JE_CORE_RESOURCECOLUMN",
                            ConditionsWrapper.builder().eq("RESOURCECOLUMN_FUNCINFO_ID", fun.getStr("JE_CORE_FUNCINFO_ID"))
                                    .eq("RESOURCECOLUMN_CODE", column.get("TABLECOLUMN_CODE"))
                                    .ne("RESOURCECOLUMN_INDEX", 1));
                    for(DynaBean rc:rcList){
                        rc.set(BeanService.KEY_TABLE_CODE, "JE_CORE_RESOURCECOLUMN");
                        rc.set("RESOURCECOLUMN_INDEX", "1");
                        rc.set("RESOURCECOLUMN_ORDER", "0");
                        metaService.update(rc);
                    }
                }

                if (!fieldList.contains(column.getStr("TABLECOLUMN_CODE"))) {
                    Boolean isUpdate = false;
                    if (fieldList.contains(column.getStr("TABLECOLUMN_OLDCODE"))) {
                        isUpdate = true;
                    }
                    if (!isUpdate) {
                        //List<Map<String,Object>> fieldListPlan = metaService.selectSql("select JE_CORE_RESOURCEFIELD_PLAN_ID from JE_CORE_RESOURCEFIELD_PLAN where PLAN_FUNCINFO_ID={0}",fun.getStr("JE_CORE_FUNCINFO_ID"));
                        /*for(Map<String,Object> map:fieldListPlan){*/
                            DynaBean rf = new DynaBean("JE_CORE_RESOURCEFIELD", false);
                            //rf.setStr("RESOURCEFIELD_PLAN_ID",map.get("JE_CORE_RESOURCEFIELD_PLAN_ID").toString());
                            rf.set(BeanService.KEY_PK_CODE, "JE_CORE_RESOURCEFIELD_ID");
                            rf.set("RESOURCEFIELD_HELP_TIP_W",660);
                            rf.set("RESOURCEFIELD_USE_SCOPE", "ALL");
                            rf.set("RESOURCEFIELD_HELP_TIP_H",400);
                            rf.set("RESOURCEFIELD_FUNCINFO_ID", fun.getStr("JE_CORE_FUNCINFO_ID"));
                            rf.set("RESOURCEFIELD_CODE", column.get("TABLECOLUMN_CODE"));
                            rf.set("RESOURCEFIELD_NAME", column.get("TABLECOLUMN_NAME"));
                            rf.setStr("RESOURCEFIELD_LABELALIGN","right");
                            //将导入的字段标识为true
                            rf.set("RESOURCEFIELD_IFIMPL", "1");
                            //是否可用  true
                            rf.set("RESOURCEFIELD_DISABLED", "1");
                            //默认序号为0
                            //rf.set("SY_ORDERINDEX", fieldOrderIndex + i + 1);
                            rf.set("SY_ORDERINDEX", 0);
                            //是否可以为空  true
                            rf.set("RESOURCEFIELD_ALLOWBLANK", "1");
                            //是否只读
                            rf.set("RESOURCEFIELD_READONLY", "0");
                            if (!Strings.isNullOrEmpty(column.getStr("TABLECOLUMN_NAME"))
                                    && (column.getStr("TABLECOLUMN_NAME").endsWith("_CODE")||column.getStr("TABLECOLUMN_NAME").endsWith("_NAME"))){
                                rf.set("RESOURCEFIELD_READONLY", "1");
                            }
                            String columnType = column.getStr("TABLECOLUMN_TYPE");
                            //数值型
                            if ("NUMBER".equals(columnType) || "FLOAT".equals(columnType)) {
                                //字段类型   默认为文本框
                                rf.set("RESOURCEFIELD_XTYPE", "numberfield");
                                if ("FLOAT".equals(columnType) && StringUtil.isNotEmpty(column.getStr("TABLECOLUMN_LENGTH"))) {
                                    String lengthStr = column.getStr("TABLECOLUMN_LENGTH");
                                    if (lengthStr.indexOf(",") != -1) {
                                        //默认小数精度
                                        rf.set("RESOURCEFIELD_CONFIGINFO", lengthStr.split(ArrayUtils.SPLIT)[1]);
                                    } else {
                                        //默认小数精度
                                        rf.set("RESOURCEFIELD_CONFIGINFO", lengthStr);
                                    }
                                } else if ("NUMBER".equals(columnType)) {
                                    //默认小数精度
                                    rf.set("RESOURCEFIELD_CONFIGINFO", "0");
                                }
                            } else if ("FLOAT2".equals(columnType)) {
                                //字段类型   默认为文本框
                                rf.set("RESOURCEFIELD_XTYPE", "numberfield");
                                //默认小数精度
                                rf.set("RESOURCEFIELD_CONFIGINFO", "2");
                            } else if ("DATE".equals(columnType)) {
                                //字段类型   默认为文本框
                                rf.set("RESOURCEFIELD_XTYPE", "datefield");
                                rf.setStr("RESOURCEFIELD_OTHERCONFIG",buildDateConfig(columnType,null));
                            } else if ("DATETIME".equals(columnType)) {
                                //字段类型   默认为文本框
                                rf.set("RESOURCEFIELD_XTYPE", "datefield");
                                rf.setStr("RESOURCEFIELD_OTHERCONFIG",buildDateConfig(columnType,null));
                            } else {
                                //字段类型   默认为文本框
                                rf.set("RESOURCEFIELD_XTYPE", "textfield");
                            }
                            //所占列数
                            rf.set("RESOURCEFIELD_COLSPAN", 1);
                            //可选可编辑   默认否
                            rf.set("RESOURCEFIELD_EDITABLE", "0");
                            rf.set("RESOURCEFIELD_HIDDEN", "1");
                            //所占行数
                            rf.set("RESOURCEFIELD_ROWSPAN", 1);
                            rf.set("RESOURCEFIELD_SYSMODE", fun.getStr("FUNCINFO_SYSMODE"));
                            rf.set("RESOURCEFIELD_ISPK", "0");
                            //根据列的添加方式 字典添加，表添加来快速初始化功能配置项
                            if (StringUtil.isNotEmpty(column.getStr("TABLECOLUMN_DICCONFIG"))) {
                                String dicOtherConfig = column.getStr("TABLECOLUMN_DICQUERYFIELD");
                                if (StringUtil.isNotEmpty(dicOtherConfig)) {
                                    if (dicOtherConfig.indexOf("cascadeField") != -1) {
                                        net.sf.json.JSONObject dicConfig = net.sf.json.JSONObject.fromObject(dicOtherConfig);
                                        String where = dicConfig.optString("where");
                                        String other = dicConfig.optString("other");
                                        rf.set("RESOURCEFIELD_XTYPE", "cbbfield");
                                        rf.set("RESOURCEFIELD_CONFIGINFO", column.getStr("TABLECOLUMN_DICCONFIG"));
                                        rf.set("RESOURCEFIELD_OTHERCONFIG", other);
                                        rf.set("RESOURCEFIELD_WHERESQL", where);
                                    } else {
                                        rf.set("RESOURCEFIELD_XTYPE", "treessfield");
                                        rf.set("RESOURCEFIELD_CONFIGINFO", column.getStr("TABLECOLUMN_DICCONFIG"));
                                        rf.set("RESOURCEFIELD_OTHERCONFIG", URLDecoder.decode("%7B%22queryField%22%3A%22" + column.getStr("TABLECOLUMN_DICQUERYFIELD") + "%22%7D "));
                                    }
                                } else {
                                    rf.set("RESOURCEFIELD_XTYPE", "cbbfield");
                                    rf.set("RESOURCEFIELD_CONFIGINFO", column.getStr("TABLECOLUMN_DICCONFIG"));
                                }
                            } else if (StringUtil.isNotEmpty(column.getStr("TABLECOLUMN_QUERYCONFIG"))) {
                                if (column.getStr("TABLECOLUMN_QUERYCONFIG").startsWith("JE_RBAC_VUSERQUERY,")) {
                                    rf.set("RESOURCEFIELD_XTYPE", "vueuserfield");
                                    rf.set("RESOURCEFIELD_CONFIGINFO", column.getStr("TABLECOLUMN_QUERYCONFIG"));
                                    rf.set("RESOURCEFIELD_OTHERCONFIG", getSelUserOtherconfig());
                                } else {
                                    rf.set("RESOURCEFIELD_XTYPE", "gridssfield");
                                    rf.set("RESOURCEFIELD_CONFIGINFO", column.getStr("TABLECOLUMN_QUERYCONFIG"));
                                }
                            }
                            if ("SY_WARNFLAG".equals(column.get("TABLECOLUMN_CODE"))) {
                                rf.set("RESOURCEFIELD_XTYPE", "cbbfield");
                                rf.set("RESOURCEFIELD_CONFIGINFO", "JE_WARNFLAG");
                            } else if ("SY_ZHMC".equals(column.get("TABLECOLUMN_CODE"))) {
                                rf.set("RESOURCEFIELD_VALUE", "@USER_ZHMC@");
                            } else if ("SY_TENANT_ID".equals(column.get("TABLECOLUMN_CODE"))) {
                                rf.set("RESOURCEFIELD_VALUE", "@USER_ZHID@");
                            } else if ("SY_ACKFLAG".equals(column.get("TABLECOLUMN_CODE"))) {
                                //是否只读
                                rf.set("RESOURCEFIELD_READONLY", "1");
                                rf.set("RESOURCEFIELD_VALUE", "0");
                                //字段类型   默认为文本框
                                rf.set("RESOURCEFIELD_XTYPE", "cbbfield");
                                //字段类型   默认为文本框
                                rf.set("RESOURCEFIELD_CONFIGINFO", "SY_ACKFLAG,SY_ACKFLAG,code,S");
                                fieldCount=fieldCount+1;
                                rf.set("SY_ORDERINDEX", fieldCount);
                            }else if("SY_AUDFLAG".equals(column.get("TABLECOLUMN_CODE"))){
                                rf.set("RESOURCEFIELD_READONLY","1");
                                rf.set("RESOURCEFIELD_VALUE","NOSTATUS");
                                rf.set("RESOURCEFIELD_XTYPE", "cbbfield");
                                rf.set("RESOURCEFIELD_CONFIGINFO", "JE_AUDFLAG,SY_AUDFLAG,code,S");
                            }else if("SY_ACKUSERNAME".equals(column.get("TABLECOLUMN_CODE"))||"SY_ACKUSERID".equals(column.get("TABLECOLUMN_CODE"))
                            ||"SY_ACKTIME".equals(column.get("TABLECOLUMN_CODE"))){
                                fieldCount=fieldCount+1;
                                rf.set("SY_ORDERINDEX", fieldCount);
                            }
                            rf.set("SY_CREATETIME", nowDate);
                            rf.set("SY_CREATEUSERID", SecurityUserHolder.getCurrentAccountRealUserId());
                            rf.set("SY_CREATEUSERNAME", SecurityUserHolder.getCurrentAccountRealUserName());
                            rf.set("SY_CREATEORGID", SecurityUserHolder.getCurrentAccountRealOrgId());
                            rf.set("SY_CREATEORGNAME", SecurityUserHolder.getCurrentAccountRealOrgName());
                            if ("1".equals(rf.getStr("RESOURCEFIELD_HIDDEN"))) {
                                rf.set("RESOURCEFIELD_FIELDLAZY", "0");
                            } else {
                                rf.set("RESOURCEFIELD_FIELDLAZY", "1");
                            }
                            rf.set("RESOURCEFIELD_DESCRIPTION", column.getStr("TABLECOLUMN_REMARK"));
                            rf.set("RESOURCEFIELD_USE_SCOPE", "ALL");
                            metaService.insert(rf);
                        /*}*/

                    } else {
                        //如果是修改列名的情况。 则修改功能中的column列编码
                        List<DynaBean> rcList = metaService.select("JE_CORE_RESOURCEFIELD",
                                ConditionsWrapper.builder().eq("RESOURCEFIELD_FUNCINFO_ID", fun.getStr("JE_CORE_FUNCINFO_ID"))
                                        .eq("RESOURCEFIELD_CODE", column.get("TABLECOLUMN_OLDCODE")));
                        for(DynaBean rc:rcList){
                            rc.set(BeanService.KEY_TABLE_CODE, "JE_CORE_RESOURCEFIELD");
                            String cType = column.getStr("TABLECOLUMN_TYPE");
                            //DATETIME :日期时间；DATE：日期
                            if("DATETIME".equals(cType) || "DATE".equals(cType)){
                                rc.setStr("RESOURCEFIELD_OTHERCONFIG",buildDateConfig(cType,rc.getStr("RESOURCEFIELD_OTHERCONFIG")));
                                rc.setStr("RESOURCEFIELD_XTYPE","datefield");
                            }


                            rc.set("RESOURCEFIELD_CODE", column.get("TABLECOLUMN_CODE"));
                            rc.set("RESOURCEFIELD_NAME", column.get("TABLECOLUMN_NAME"));
                            metaService.update(rc);
                        }

                    }
                }
            }
            //批量更新功能列的信息
            resColumnService.batchSortOutColumnInfoByFuncId(funId);
        }
        //设置键和字段全为已经创建   在功能字段处理之后
        metaService.executeSql("UPDATE JE_CORE_TABLECOLUMN SET TABLECOLUMN_ISCREATE='1',TABLECOLUMN_OLDCODE=TABLECOLUMN_CODE,TABLECOLUMN_OLDUNIQUE=TABLECOLUMN_UNIQUE,TABLECOLUMN_TABLECODE={0} WHERE TABLECOLUMN_RESOURCETABLE_ID={1}", tableCode, resourceTableId);
        metaService.executeSql("UPDATE JE_CORE_TABLEKEY SET TABLEKEY_ISCREATE='1',TABLEKEY_TABLECODE={0} WHERE TABLEKEY_RESOURCETABLE_ID={1}", tableCode, resourceTableId);
        metaService.executeSql("UPDATE JE_CORE_TABLEINDEX SET TABLEINDEX_ISCREATE='1',TABLEINDEX_TABLECODE={0} WHERE TABLEINDEX_RESOURCETABLE_ID={1}", tableCode, resourceTableId);
        //metaService.executeSql("UPDATE JE_CORE_TABLETRACE SET TABLETRACE_SFYY='1' WHERE TABLETRACE_RESOURCETABLE_ID={0} and TABLETRACE_SFYY='0'", resourceTableId);

        /**---------------------------功能中增加字典结束-----------------------------------------*/
        keys = metaService.select("JE_CORE_TABLEKEY",
                ConditionsWrapper.builder().eq("TABLEKEY_RESOURCETABLE_ID", resourceTableId));
        resourceTable.set("RESOURCETABLE_OLDTABLECODE", resourceTable.getStr("RESOURCETABLE_TABLECODE"));
        resourceTable.set("RESOURCETABLE_PKCODE", "");
        updateTableKey(resourceTable, keys);
        tableCache.removeCache(resourceTable.getStr("RESOURCETABLE_TABLECODE"));
        dynaCache.removeCache(resourceTable.getStr("RESOURCETABLE_TABLECODE"));
        //清空mybatis缓存
        //metaService.clearMyBatisTableCache(resourceTable.getStr("RESOURCETABLE_TABLECODE"));
        developLogService.doDevelopLog("applyTable","应用资源表","table","资源表",resourceTable.getStr("RESOURCETABLE_TABLENAME"), resourceTable.getStr("RESOURCETABLE_TABLECODE"),resourceTable.getStr("JE_CORE_RESOURCETABLE_ID"),resourceTable.getStr("SY_PRODUCT_ID"));
    }

    private String getSelUserOtherconfig() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("deptQuery","DEPT");
        return jsonObject.toJSONString();
    }

    private String buildDateConfig(String cType, String config) {
        String dateType = "";
        if("DATETIME".equals(cType)){
            dateType="dateTime";
        }
        if("DATE".equals(cType)){
            dateType="date";
        }
        JSONObject jsonObject=null;
        if(StringUtil.isNotEmpty(config)){
            jsonObject = JSON.parseObject(config);
            if(jsonObject.containsKey("dateType")){
                jsonObject.put("dateType",dateType);
            }
        }else {
            jsonObject = new JSONObject();
            jsonObject.put("dateType",dateType);
        }
        return jsonObject.toJSONString();

    }

    @Override
    @Transactional
    public boolean updateTable(String resourceTableId, Boolean isFuncs) {
        boolean success = true;
        String result = checkTableForApply(resourceTableId);
        if(StringUtil.isNotEmpty(result)){
            throw new PlatformException(result, PlatformExceptionEnum.UNKOWN_ERROR);
        }
        DynaBean resourceTable = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", resourceTableId);
        List<DbModel> dbModels = pcDataService.loadTableColumnBySql(resourceTable.getStr("RESOURCETABLE_TABLECODE"));
        List<String> arraySql = generateUpdateDDL(resourceTableId, dbModels);
//            todo 神通数据-如果存在SY_PARENT外键，就不对此外键进行操作 huxaunhua
        if (JEDatabase.getCurrentDatabase().equalsIgnoreCase(ConstantVars.STR_SHENTONG)
                && metaService.countBySql("select count(*) from user_cons_columns where table_name='" + resourceTable.get("RESOURCETABLE_TABLECODE") + "' and column_name='SY_PARENT'") > 0) {
            arraySql.removeIf(s -> s.contains("foreign key (SY_PARENT)"));
        }
        for (String sql : arraySql) {
            sql = sql.replaceAll("\n", "");
            if (StringUtil.isNotEmpty(sql)) {
                metaService.executeSql(sql);
            }
        }
        afterTableUpdated(resourceTableId);
        return success;
    }

    @Override
    public List<String> generateCreateDDL(String resourceTableId) {
        DynaBean resourceTable = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", resourceTableId);
        List<DynaBean> columns = metaService.select(ConditionsWrapper.builder()
                .table("JE_CORE_TABLECOLUMN")
                .apply("TABLECOLUMN_RESOURCETABLE_ID={0} ORDER BY TABLECOLUMN_CLASSIFY ASC,SY_ORDERINDEX ASC", resourceTable.getStr("JE_CORE_RESOURCETABLE_ID")));
        List<DynaBean> keys = metaService.select(ConditionsWrapper.builder()
                .table("JE_CORE_TABLEKEY")
                .apply("TABLEKEY_RESOURCETABLE_ID={0} ORDER BY TABLEKEY_CLASSIFY DESC,SY_ORDERINDEX ASC", resourceTable.getStr("JE_CORE_RESOURCETABLE_ID")));
        List<DynaBean> indexs = metaService.select(ConditionsWrapper.builder()
                .table("JE_CORE_TABLEINDEX")
                .apply("TABLEINDEX_RESOURCETABLE_ID={0}", resourceTable.getStr("JE_CORE_RESOURCETABLE_ID")));

        resourceTable.set(BeanService.KEY_TABLE_COLUMNS, columns);
        resourceTable.set(BeanService.KEY_TABLE_KEYS, keys);
        resourceTable.set(BeanService.KEY_TABLE_INDEXS, indexs);

        //清空缓存并传入带有列和键的表资源对象
        List<String> arraySql = BuildingSqlFactory.build().getDDL4CreateTable(resourceTable);
        return arraySql;
    }

    @Override
    @Transactional
    public DynaBean afterTableCreated(String resourceTableId) {
        DynaBean resourceTable = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", resourceTableId);
        String tableCode = resourceTable.getStr("RESOURCETABLE_TABLECODE");

        List<DynaBean> keys = metaService.select(ConditionsWrapper.builder()
                .table("JE_CORE_TABLEKEY")
                .apply("TABLEKEY_RESOURCETABLE_ID={0} ORDER BY TABLEKEY_CLASSIFY DESC,SY_ORDERINDEX ASC", resourceTable.getStr("JE_CORE_RESOURCETABLE_ID")));
        List<DynaBean> indexs = metaService.select(ConditionsWrapper.builder()
                .table("JE_CORE_TABLEINDEX")
                .apply("TABLEINDEX_RESOURCETABLE_ID={0}", resourceTable.getStr("JE_CORE_RESOURCETABLE_ID")));


        boolean use = false;
        List<String> parentTableCodes = new ArrayList<String>();
        for (DynaBean key : keys) {
            if ("Foreign".equals(key.get("TABLEKEY_TYPE"))) {
                //把自己的TableCode 写到父表的childTableCodes中用","分开
                DynaBean fatherTable = metaService.selectOne("JE_CORE_RESOURCETABLE",
                        ConditionsWrapper.builder().eq("RESOURCETABLE_TABLECODE", key.getStr("TABLEKEY_LINKTABLE")));
                String childTableCodes = fatherTable.getStr("RESOURCETABLE_CHILDTABLECODES");
                if (StringUtil.isNotEmpty(childTableCodes)) {
                    //不是空的操作
                    if (childTableCodes.indexOf(tableCode) == -1) {
                        childTableCodes = childTableCodes + "," + tableCode;
                    }
                    fatherTable.set("RESOURCETABLE_CHILDTABLECODES", childTableCodes);
                } else {
                    fatherTable.set("RESOURCETABLE_CHILDTABLECODES", tableCode);
                }
                parentTableCodes.add(fatherTable.getStr("RESOURCETABLE_TABLECODE"));
                use = true;
                fatherTable.set(BeanService.KEY_TABLE_CODE, "JE_CORE_RESOURCETABLE");
                metaService.update(fatherTable);
            } else if ("Primary".equals(key.getStr("TABLEKEY_TYPE"))) {
                resourceTable.set("RESOURCETABLE_PKCODE", key.getStr("TABLEKEY_COLUMNCODE"));
            }
        }

        //设置其用到了外键
        if (use) {
            for (String parentTableCode : parentTableCodes) {
                String tableCodes = resourceTable.getStr("RESOURCETABLE_PARENTTABLECODES");
                if (StringUtil.isNotEmpty(tableCodes)) {
                    //不是空的操作
                    if (tableCodes.indexOf(parentTableCode) == -1) {
                        tableCodes = tableCodes + "," + parentTableCode;
                    }
                    resourceTable.set("RESOURCETABLE_PARENTTABLECODES", tableCodes);
                } else {
                    resourceTable.set("RESOURCETABLE_PARENTTABLECODES", parentTableCode);
                }
            }
            resourceTable.set("RESOURCETABLE_ISUSEFOREIGNKEY", "1");
        } else {
            resourceTable.set("RESOURCETABLE_ISUSEFOREIGNKEY", "0");
        }
        resourceTable.set("RESOURCETABLE_OLDTABLECODE", resourceTable.getStr("RESOURCETABLE_TABLECODE"));
        resourceTable.set(BeanService.KEY_TABLE_CODE, "JE_CORE_RESOURCETABLE");
        resourceTable.set("RESOURCETABLE_ISCREATE", "1");
        metaService.update(resourceTable);
        //设置键和字段全为已经创建
        metaService.executeSql("UPDATE JE_CORE_TABLECOLUMN SET TABLECOLUMN_ISCREATE='1',TABLECOLUMN_OLDCODE=TABLECOLUMN_CODE,TABLECOLUMN_OLDUNIQUE=TABLECOLUMN_UNIQUE,TABLECOLUMN_TABLECODE={0} WHERE TABLECOLUMN_RESOURCETABLE_ID={1}", tableCode, resourceTableId);
        metaService.executeSql("UPDATE JE_CORE_TABLEKEY SET TABLEKEY_ISCREATE='1',TABLEKEY_TABLECODE={0} WHERE TABLEKEY_RESOURCETABLE_ID={1}", tableCode, resourceTableId);
        metaService.executeSql("UPDATE JE_CORE_TABLEINDEX SET TABLEINDEX_ISCREATE='1',TABLEINDEX_TABLECODE={0} WHERE TABLEINDEX_RESOURCETABLE_ID={1}", tableCode, resourceTableId);

        //如果是树形则插入一条ROOT数据
        DynaBean bean = new DynaBean(resourceTable.getStr("RESOURCETABLE_TABLECODE"), false);
        bean.setStr("RESOURCETABLE_TYPE",resourceTable.getStr("RESOURCETABLE_TYPE"));
        bean.setStr("RESOURCETABLE_TABLECODE",resourceTable.getStr("RESOURCETABLE_TABLECODE"));
        bean.setStr("RESOURCETABLE_MOREROOT",resourceTable.getStr("RESOURCETABLE_MOREROOT"));
        if (resourceTable.get("RESOURCETABLE_TYPE").equals(TableType.TREETABLE) && !"1".equals(resourceTable.get("RESOURCETABLE_MOREROOT"))) {
            JSONTreeNode template = metaBeanService.buildJSONTreeNodeTemplate((List<DynaBean>) metaBeanService.getResourceTable(resourceTable.getStr("RESOURCETABLE_TABLECODE")).get(BeanService.KEY_TABLE_COLUMNS));
            bean.set(BeanService.KEY_PK_CODE, template.getId());
            bean.set(template.getId(), "ROOT");
            bean.set(template.getParent(), null);
            bean.set(template.getText(), "ROOT");
            bean.set(template.getCode(), "ROOT");
            bean.set("SY_NODETYPE", "ROOT");
            bean.set("SY_PATH", "/ROOT");
            bean.set("SY_LAYER", 0);
            bean.set("SY_ORDERINDEX", 1);
            bean.set("SY_TREEORDERINDEX", StringUtil.preFillUp("1", 6, '0'));
            commonService.buildModelCreateInfo(bean);
            if(PRODUCT_CORE_META.equals(resourceTable.getStr("SY_PRODUCT_CODE"))){
                metaService.insert(bean);
            }
        }
        metaTableTraceService.saveTableTrace("JE_CORE_RESOURCETABLE", null, resourceTable, "INSERT", resourceTableId, "1");
        return bean;
    }

    @Override
    public List<String> generateRemoveDDL(String ids) {
        List<String> arraySql = Lists.newArrayList();
        String[] idArray = ids.split(ArrayUtils.SPLIT);
        for (String id : idArray) {
            //数据删除
            DynaBean resourceTable = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", id);
            //删除已经被创建的表
            if (resourceTable != null && "1".equals(resourceTable.getStr("RESOURCETABLE_ISCREATE"))) {
                if ("VIEW".equals(resourceTable.getStr("RESOURCETABLE_TYPE"))) {
                    arraySql.add("DROP VIEW " + resourceTable.getStr("RESOURCETABLE_TABLECODE"));
                } else {
                    //判断是否有子表，有子表不允许删除
                    String childCodes = resourceTable.getStr("RESOURCETABLE_CHILDTABLECODES", "");
                    if (StringUtil.isNotEmpty(childCodes)) {
                        throw new PlatformException(MessageUtils.getMessage("table.detele.constraint"), PlatformExceptionEnum.JE_CORE_TABLE_DELETE_ERROR);
                    }
                    arraySql.add("DROP TABLE " + resourceTable.getStr("RESOURCETABLE_TABLECODE"));
                }
            }
        }
        return arraySql;
    }


    @Override
    @Transactional
    public String doHardDelete(String ids) {
        String[] idArray = ids.split(ArrayUtils.SPLIT);
        List<DynaBean> tablesList = metaService.select("JE_CORE_RESOURCETABLE",
                ConditionsWrapper.builder()
                        .in("JE_CORE_RESOURCETABLE_ID", idArray));
        for (DynaBean table : tablesList) {
            String tableCode = table.getStr("RESOURCETABLE_TABLECODE");
            String deleteTableDDl = getDeleteTableDDl(table);
            if (!StringUtil.isEmpty(deleteTableDDl)) {
                metaService.executeSql(deleteTableDDl);
            }
            //删除元数据
            deleteTableMeta(table.getStr("JE_CORE_RESOURCETABLE_ID"));
            developLogService.doDevelopLog("hardDelete","物理删除","table","资源表",table.getStr("RESOURCETABLE_TABLENAME"), tableCode,table.getStr("JE_CORE_RESOURCETABLE_ID"),table.getStr("SY_PRODUCT_ID"));
        }
        return null;
    }

    /**
     * 获取删除表DDL语句
     *
     * @param ids 主键
     * @return
     */
    @Override
    public String getDeleteTableDDlByIds(String ids) {
        StringBuffer sb = new StringBuffer();
        String[] idArray = ids.split(ArrayUtils.SPLIT);
        List<DynaBean> tablesList = metaService.select("JE_CORE_RESOURCETABLE",
                ConditionsWrapper.builder()
                        .in("JE_CORE_RESOURCETABLE_ID", idArray));
        for (DynaBean table : tablesList) {
            if (table != null) {
                sb.append(getDeleteTableDDl(table));
            }
        }
        return sb.toString();
    }

    /**
     * 获取删除表的ddl语句
     *
     * @param resourceTable 业务bean
     * @return
     */
    private String getDeleteTableDDl(DynaBean resourceTable) {
        //执行DDL
        String DDl = "";
        if ("1".equals(resourceTable.getStr("RESOURCETABLE_ISCREATE"))) {
            if ("VIEW".equals(resourceTable.getStr("RESOURCETABLE_TYPE"))) {
                try {
                    DDl = String.format("DROP VIEW %s ;", resourceTable.getStr("RESOURCETABLE_TABLECODE"));
                } catch (Exception e) {
                    throw new PlatformException(MessageUtils.getMessage("view.isEmpty.clear"), PlatformExceptionEnum.JE_CORE_TABLE_DELETE_ERROR);
                }
            } else {
                //判断是否有子表，有子表不允许删除
                String childCodes = resourceTable.getStr("RESOURCETABLE_CHILDTABLECODES", "");
                if (StringUtil.isNotEmpty(childCodes)) {
                    throw new PlatformException(MessageUtils.getMessage("table.detele.constraint"), PlatformExceptionEnum.JE_CORE_TABLE_DELETE_ERROR);
                }
                try {
                    DDl = String.format("DROP TABLE %s ;", resourceTable.getStr("RESOURCETABLE_TABLECODE"));
                } catch (Exception d) {
                    throw new PlatformException(MessageUtils.getMessage("table.isEmpty"), PlatformExceptionEnum.JE_CORE_TABLE_DELETE_ERROR);
                }

            }
        }
        return DDl;
    }

    @Override
    public List<Map<String, Object>> getRelation(DynaBean tableInfo) {
        List<Map<String, Object>> funcTree = new ArrayList<>();
        //功能信息
        List<DynaBean> funcList = metaService.select("JE_CORE_FUNCINFO", ConditionsWrapper.builder().eq("FUNCINFO_TABLENAME", tableInfo.getStr("RESOURCETABLE_TABLECODE")));
        for (DynaBean func : funcList) {
            Boolean isExist = false;
            String funcId = func.getStr("JE_CORE_FUNCINFO_ID");
            for (Map<String, Object> m : funcTree) {
                if (m.get("JE_CORE_FUNCINFO_ID").equals(funcId)) {
                    isExist = true;
                    break;
                }
            }
            if (isExist) {
                continue;
            }
            //查找第一层功能
            Map<String, Object> layerMap = getlayerInfo(func);
            int layerInt = (int) layerMap.get("layerInt");
            String layerId = (String) layerMap.get("id");
            //查找所有子功能
            List<DynaBean> childFuncs = metaService.select("JE_CORE_FUNCINFO",
                    ConditionsWrapper.builder().like("SY_PATH", layerId).orderByAsc("SY_PATH", "SY_TREEORDERINDEX"));
            for (DynaBean childFunc : childFuncs) {
                addChild(childFunc, funcTree, layerInt, tableInfo.getStr("RESOURCETABLE_TABLECODE"));
            }
        }
        return funcTree;
    }

    private void addChild(DynaBean dynaBean, List<Map<String, Object>> funcTree, int layerInt, String tableName) {
        Map<String, Object> funcMap = new HashMap<>();
        int indentation = dynaBean.getStr("SY_PATH").split("/").length;
        funcMap.put("INDENTATION", indentation - layerInt);
        funcMap.put("JE_CORE_FUNCINFO_ID", dynaBean.getStr("JE_CORE_FUNCINFO_ID"));
        funcMap.put("SY_PATH", dynaBean.getStr("SY_PATH"));
        funcMap.put("SY_PRODUCT_ID", dynaBean.getStr("SY_PRODUCT_ID"));
        funcMap.put("FUNCINFO_ICON", dynaBean.getStr("FUNCINFO_ICON"));
        funcMap.put("FUNCINFO_FUNCNAME", dynaBean.getStr("FUNCINFO_FUNCNAME"));
        funcMap.put("FUNCINFO_FUNCCODE", dynaBean.getStr("FUNCINFO_FUNCCODE"));
        funcMap.put("FUNCINFO_TABLENAME", dynaBean.getStr("FUNCINFO_TABLENAME"));
        if (tableName.equals(dynaBean.getStr("FUNCINFO_TABLENAME"))) {
            funcMap.put("highlight", "1");
        }
        funcTree.add(funcMap);
    }

    private Map<String, Object> getlayerInfo(DynaBean func) {
        Map<String, Object> result = new HashMap<>();
        String SY_PATH = func.getStr("SY_PATH");
        String[] funcIds = SY_PATH.split("/");
        for (String funcId : funcIds) {
            if (Strings.isNullOrEmpty(funcId) || funcId.equals("ROOT")) {
                continue;
            }
            DynaBean funcInfo = metaService.selectOneByPk("JE_CORE_FUNCINFO", funcId);
            String type = funcInfo.getStr("FUNCINFO_NODEINFOTYPE");
            if (type.equals("FUNC") || type.equals("FUNCFIELD")) {
                result.put("id", funcInfo.getStr("JE_CORE_FUNCINFO_ID"));
                result.put("layerInt", funcInfo.getStr("SY_PATH").split("/").length);
                break;
            }
        }
        return result;
    }

    @Override
    public List<DynaBean> selectByColumnCode(String tableCode) {
        List<DynaBean> columns = metaService.select("JE_CORE_TABLECOLUMN",
                ConditionsWrapper.builder().eq("TABLECOLUMN_TABLECODE", tableCode));
        return columns;
    }

    private List<Map<String, Object>> buildFuncTree(List<Map<String, Object>> list, String firstModelId, String funcId) {
        List<Map<String, Object>> listTree = new ArrayList<>();
        Map<String, Object> node = new HashMap<>();
        for (Map<String, Object> map : list) {
            String id = map.get("JE_CORE_FUNCINFO_ID").toString();
            if (id.equals(firstModelId)) {
                node = map;
                node.put("level", 1);
                list.remove(map);
                break;
            }
        }
        listTree.add(node);
        createTreeData(list, node, listTree, funcId);
        return listTree;
    }

    private void createTreeData(List<Map<String, Object>> list, Map<String, Object> root, List<Map<String, Object>> listTree, String funcId) {
        String id = "";
        if (root.size() != 0) {
            id = root.get("JE_CORE_FUNCINFO_ID").toString();
        }
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = list.get(i);
            String parentId = map.get("SY_PARENT").toString();
            if (funcId.equals(map.get("JE_CORE_FUNCINFO_ID").toString())) {
                map.put("isHighlight", "1");
            }
            if (id.equals(parentId)) {
                map.put("level", listTree.size() + 1);
                listTree.add(map);
                createTreeData(list, map, listTree, funcId);
            }
            if (i == list.size() - 1) {
                return;
            }
        }
    }

    private String getSql(String[] arr) {
        String sql = "";
        for (String str : arr) {
            if (!"ROOT".equals(str)) {
                sql += "'" + str + "',";
            }
        }
        sql = sql.substring(0, sql.length() - 1);
        return sql;
    }

    private void createTreeChildren(List<Map<String, Object>> list, Map<String, Object> root) {
        String id = root.get("JE_CORE_FUNCINFO_ID").toString();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = list.get(i);
            String parentId = map.get("SY_PARENT").toString();
            if (id.equals(parentId)) {
                root.put("children", new ArrayList<HashMap>());
                ((List<Map>) root.get("children")).add(map);
                if (((List<Map>) root.get("children")).size() > 0) {
                    root.put("leaf", false);
                }
                createTreeChildren(list, map);
            }
            if (i == list.size() - 1) {
                return;
            }
        }
    }

    /**
     * 删除元数据
     *
     */
    @Override
    public void deleteTableMeta(String id) {
        DynaBean resourceTable = metaService.selectOneByPk("JE_CORE_RESOURCETABLE",id);
        List<DynaBean> keys = metaService.select(ConditionsWrapper.builder().table("JE_CORE_TABLEKEY").eq("TABLEKEY_RESOURCETABLE_ID", id));
        for (DynaBean key : keys) {
            //如果存在外键
            if ("Foreign".equals(key.get("TABLEKEY_TYPE"))) {
                //清楚他在主表中的数据
                String tableCode = resourceTable.getStr("RESOURCETABLE_TABLECODE");
                DynaBean fatherTable = metaService.selectOne("JE_CORE_RESOURCETABLE",
                        ConditionsWrapper.builder().eq("RESOURCETABLE_TABLECODE", key.getStr("TABLEKEY_LINKTABLE")));
                if (fatherTable != null) {
                    String childTableCodes = fatherTable.getStr("RESOURCETABLE_CHILDTABLECODES");
                    if (StringUtil.isNotEmpty(childTableCodes)) {
                        childTableCodes = Arrays.stream(childTableCodes.split(",")).filter(v -> !v.equals(tableCode)).collect(Collectors.joining(","));
                        fatherTable.set("RESOURCETABLE_CHILDTABLECODES", childTableCodes);
                        fatherTable.set(BeanService.KEY_TABLE_CODE, "JE_CORE_RESOURCETABLE");
                        metaService.update(fatherTable);
                    }
                }
            }
        }

        metaService.executeSql("DELETE FROM JE_CORE_RESOURCETABLE WHERE JE_CORE_RESOURCETABLE_ID={0}", id);
        metaService.executeSql("DELETE FROM JE_CORE_TABLEVIEW WHERE TABLEVIEW_RESOURCETABLE_ID={0}", id);
        metaService.executeSql("DELETE FROM JE_CORE_VIEWCASCADE WHERE JE_CORE_RESOURCETABLE_ID={0}", id);

        //删除功能相关数据
        List<DynaBean> funcList = metaService.select("JE_CORE_FUNCINFO",
                ConditionsWrapper.builder().eq("FUNCINFO_TABLENAME",resourceTable.getStr("RESOURCETABLE_TABLECODE")));
        for(DynaBean func:funcList){
            funcInfoService.removeFuncInfoById(func.getStr("JE_CORE_FUNCINFO_ID"));
        }
    }

    @Override
    public String translate(String strData, String sql) {
        Map<String,String> map  = new HashMap<>();
        ViewDdlVo viewDdlVo = JSONObject.parseObject(strData, ViewDdlVo.class);
        List<ViewColumn> viewColumns =viewDdlVo.getViewColumn();
        for(ViewColumn viewColumn:viewColumns){
            String mainTableCode = viewColumn.getMainTableCode();
            String mainColumn = viewColumn.getMainColumn();
            String mainTableName = viewColumn.getMainTableName();
            if(StringUtil.isNotEmpty(mainTableCode)){
                map.put(mainTableCode.toUpperCase(),mainTableName);
            }
            DynaBean mainColumnDynaBean = metaService.selectOne("JE_CORE_TABLECOLUMN",
                    ConditionsWrapper.builder().eq("TABLECOLUMN_TABLECODE",mainTableCode).eq("TABLECOLUMN_CODE",mainColumn));
            if(mainColumnDynaBean!=null){
                map.put(mainTableCode.toUpperCase()+"."+mainColumn.toUpperCase(),mainTableName+"."+mainColumnDynaBean.getStr("TABLECOLUMN_NAME"));
            }

            String targetTableCode = viewColumn.getTargetTableCode();
            String targetColumn = viewColumn.getTargetColumn();
            String targetTableName = viewColumn.getTargetTableName();
            if(StringUtil.isNotEmpty(targetTableCode)){
                map.put(targetTableCode.toUpperCase(),targetTableName);
            }
            DynaBean targetColumnDynaBean = metaService.selectOne("JE_CORE_TABLECOLUMN",
                    ConditionsWrapper.builder().eq("TABLECOLUMN_TABLECODE",targetTableCode).eq("TABLECOLUMN_CODE",targetColumn));
            if(targetColumnDynaBean!=null){
                map.put(targetTableCode.toUpperCase()+"."+targetColumn.toUpperCase(),targetTableName+"."+targetColumnDynaBean.getStr("TABLECOLUMN_NAME"));
            }

        }

        List<ViewOuput> viewOuputs =viewDdlVo.getViewOuput();
        for(ViewOuput viewOuput:viewOuputs){
            String tableCode = viewOuput.getTableCode();
            String column = viewOuput.getColumn();
            String value = viewOuput.getValue();

            if((tableCode+"."+column).equals(value)){
                List<Map<String,Object>> list = metaService.selectSql("select t.TABLECOLUMN_NAME,r.RESOURCETABLE_TABLENAME from JE_CORE_TABLECOLUMN t,JE_CORE_RESOURCETABLE r where t.TABLECOLUMN_RESOURCETABLE_ID=r.JE_CORE_RESOURCETABLE_ID and t.TABLECOLUMN_TABLECODE={0} and t.TABLECOLUMN_CODE={1}",tableCode,column);
                if(list!=null && list.size()>0){
                    Map<String,Object> columnMap = list.get(0);
                    String tableName = columnMap.get("RESOURCETABLE_TABLENAME")==null?"":columnMap.get("RESOURCETABLE_TABLENAME").toString();
                    String name = columnMap.get("TABLECOLUMN_NAME")==null?"":columnMap.get("TABLECOLUMN_NAME").toString();
                    map.put(value,tableName+"."+name);
                }
            }
        }

        sql = sql.toUpperCase();
        String sqlNew = sql.replaceAll("\\s+", " ");
        String[] arr = sqlNew.split(" ");

        for(String str:arr){
            //特殊符号，替换为空格
            str = replaceSpecialChar(str);
            str = str.replaceAll("\\s+", " ");
            String[] strArr = str.split(" ");
            for(String s:strArr){
                if(map.containsKey(s)){
                    sql = sql.replaceFirst(s,map.get(s));
                }
            }

        }
        return sql;
    }

    private String replaceSpecialChar(String str) {
        //特殊符号
        List<String> specialStr = Lists.newArrayList(
                "=",">","<","(",")","!",","
        );
        for(String s:specialStr){
            if(str.contains(s)){
                str = str.replace(s," ");
            }
        }

        return str;
    }


    /**
     * 导入表
     *
     * @param table
     * @return
     */
    @Override
    @Transactional
    public DynaBean impTable(DynaBean table) {
        table = beforeImportBuildDynabeanInfo(table);
        DataBaseUtils.buildDynabeanTableInfo(table);
        if ("1".equals(table.getStr("RESOURCETABLE_ISCREATE"))) {
            afterImportMetaInfo(table, null);
        }
        return table;
    }

    /**
     * 导入前buildTableInfo信息
     *
     * @param table
     */
    @Override
    public DynaBean beforeImportBuildDynabeanInfo(DynaBean table) {
        String uuid = JEUUID.uuid();
        table.setStr(BeanService.KEY_TABLE_CODE, "JE_CORE_RESOURCETABLE");
        table.set("JE_CORE_RESOURCETABLE_ID", uuid);
        commonService.buildResourceTable(table);
        if (StringUtil.isNotEmpty(table.getStr("SY_PATH"))) {
            table.set("SY_PATH", table.getStr("SY_PATH") + "/" + uuid);
        }
        return table;
    }

    /**
     * 添加表的元数据信息 列，键，索引
     *
     * @param table
     */
    @Override
    public DynaBean afterImportMetaInfo(DynaBean table, List<Map<String, Object>> lists) {
        String parenttablecodes = table.getStr("RESOURCETABLE_PARENTTABLECODES");
        table.setStr(BeanService.KEY_TABLE_CODE, "JE_CORE_RESOURCETABLE");
        DynaBean pareentTable = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", table.getStr("SY_PARENT"));
        List<DynaBean> columns = (List<DynaBean>) table.getDynaBeanList(BeanService.KEY_TABLE_COLUMNS);
        List<DynaBean> keys = (List<DynaBean>) table.getDynaBeanList(BeanService.KEY_TABLE_KEYS);
        List<DynaBean> indexs = (List<DynaBean>) table.getDynaBeanList(BeanService.KEY_TABLE_INDEXS);
        table.remove(BeanService.KEY_TABLE_COLUMNS);
        table.remove(BeanService.KEY_TABLE_KEYS);

        String nowDate = DateUtils.formatDateTime(new Date());
        table.set("SY_JECORE", "0");
        table.set("SY_JESYS", "0");
        table.set("SY_CREATETIME", nowDate);
        table.set("SY_CREATEUSERID", SecurityUserHolder.getCurrentAccountRealUserId());
        table.set("SY_CREATEUSERNAME", SecurityUserHolder.getCurrentAccountRealUserName());
        table.set("SY_CREATEORGID", SecurityUserHolder.getCurrentAccountRealOrgId());
        table.set("SY_CREATEORGNAME", SecurityUserHolder.getCurrentAccountRealOrgName());
        table.set("RESOURCETABLE_OLDTABLECODE", table.getStr("RESOURCETABLE_TABLECODE"));
        table.set("SY_PRODUCT_ID", pareentTable.getStr("SY_PRODUCT_ID"));
        table.set("SY_PRODUCT_NAME", pareentTable.getStr("SY_PRODUCT_NAME"));
        table.set("SY_PRODUCT_CODE", pareentTable.getStr("SY_PRODUCT_CODE"));
        table.setStr("SY_NODETYPE","LEAF");
        String RESOURCETABLE_TYPE = table.getStr("RESOURCETABLE_TYPE");
        if ("VIEW".equals(RESOURCETABLE_TYPE)) {
            String ddl = mateViewService.getViewCreateSql(table.getStr("RESOURCETABLE_TABLECODE"), lists);
            String viewDdl = "CREATE VIEW " + table.getStr("RESOURCETABLE_TABLECODE") + " AS " + ddl;
            try {
                viewDdl = ParseBuildingSqlFactory.build().beautifyCreateViewDdl(viewDdl);
            } catch (SQLSyntaxErrorException e) {
                e.printStackTrace();
            }
            table.set("RESOURCETABLE_SQL", viewDdl);
        }
        /**
         * 导入的表，默认的表名为表编码
         * 2022.1.24 变更为前端传表名称，故注释此代码
         */
        //table.set("RESOURCETABLE_TABLENAME", table.getStr("RESOURCETABLE_TABLECODE"));
        metaService.insert(table);
        for (DynaBean column : columns) {
            column.table("JE_CORE_TABLECOLUMN");
            column.set(BeanService.KEY_PK_CODE, "JE_CORE_TABLECOLUMN_ID");
            column.set("SY_CREATETIME", nowDate);
            column.set("SY_CREATEUSERID", SecurityUserHolder.getCurrentAccountRealUserId());
            column.set("SY_CREATEUSERNAME", SecurityUserHolder.getCurrentAccountRealUserName());
            column.set("SY_CREATEORGID", SecurityUserHolder.getCurrentAccountRealOrgId());
            if (Strings.isNullOrEmpty(column.getStr("TABLECOLUMN_NAME")) || "null".equals(column.getStr("TABLECOLUMN_NAME"))) {
                column.setStr("TABLECOLUMN_NAME", column.getStr("TABLECOLUMN_CODE"));
            }
            column.set("SY_CREATEORGNAME", SecurityUserHolder.getCurrentAccountRealOrgName());
            column.set("TABLECOLUMN_OLDCODE", column.getStr("TABLECOLUMN_CODE"));
            column.set("TABLECOLUMN_TABLECODE", table.getStr("RESOURCETABLE_TABLECODE"));
            column.set("TABLECOLUMN_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID"));
            if ("0".equals(column.getStr("TABLECOLUMN_LENGTH"))) {
                column.set("TABLECOLUMN_LENGTH", "");
            }
            metaService.insert(column);
        }
        for (DynaBean key : keys) {
            key.table("JE_CORE_TABLEKEY");
            key.set(BeanService.KEY_TABLE_CODE, "JE_CORE_TABLEKEY");
            key.set("SY_CREATETIME", nowDate);
            key.set("SY_CREATEUSERID", SecurityUserHolder.getCurrentAccountRealUserId());
            key.set("SY_CREATEUSERNAME", SecurityUserHolder.getCurrentAccountRealUserName());
            key.set("SY_CREATEORGID", SecurityUserHolder.getCurrentAccountRealOrgId());
            key.set("SY_CREATEORGNAME", SecurityUserHolder.getCurrentAccountRealOrgName());
            key.set("TABLEKEY_TABLECODE", table.getStr("RESOURCETABLE_TABLECODE"));
            key.set("TABLEKEY_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID"));
            metaService.insert(key);
        }
        for (DynaBean index : indexs) {
            index.table("JE_CORE_TABLEINDEX");
            index.set(BeanService.KEY_TABLE_CODE, "JE_CORE_TABLEINDEX");
            index.set("SY_CREATETIME", nowDate);
            index.set("SY_CREATEUSERID", SecurityUserHolder.getCurrentAccountRealUserId());
            index.set("SY_CREATEUSERNAME", SecurityUserHolder.getCurrentAccountRealUserName());
            index.set("SY_CREATEORGID", SecurityUserHolder.getCurrentAccountRealOrgId());
            index.set("SY_CREATEORGNAME", SecurityUserHolder.getCurrentAccountRealOrgName());
            index.set("TABLEINDEX_TABLECODE", table.getStr("RESOURCETABLE_TABLECODE"));
            index.set("TABLEINDEX_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID"));
            metaService.insert(index);
        }
        /** 添加子外键主子表关系 **/
        if (StringUtil.isNotEmpty(parenttablecodes)) {
            keys = metaService.select("JE_CORE_TABLEKEY",
                    ConditionsWrapper.builder().eq("TABLEKEY_RESOURCETABLE_ID", table.getPkValue()));
            table.set("RESOURCETABLE_OLDTABLECODE", table.getStr("RESOURCETABLE_TABLECODE"));
            table.set("RESOURCETABLE_PKCODE", "");
            updateTableKey(table, keys);
        }
        developLogService.doDevelopLog("IMPORT","导入表","TABLE","资源表",table.getStr("RESOURCETABLE_TABLENAME"), table.getStr("RESOURCETABLE_TABLECODE"),table.getStr("JE_CORE_RESOURCETABLE_ID"),table.getStr("SY_PRODUCT_ID"));
        return table;
    }

    @Override
    @Transactional
    public DynaBean syncTable(DynaBean table, List<DbModel> dbModels, boolean isDdl) {
        DynaBean tableInfo = new DynaBean("JE_CORE_RESOURCETABLE", false);
        tableInfo.set("RESOURCETABLE_TABLECODE", table.getStr("RESOURCETABLE_TABLECODE"));
        tableInfo.set("RESOURCETABLE_ISCREATE", "1");
        DataBaseUtils.buildDynabeanTableInfo(tableInfo);
        List<DynaBean> columnsList = (List<DynaBean>) tableInfo.get(BeanService.KEY_TABLE_COLUMNS);
        Map<String, String> columnMap = new HashMap<>();
        for (DynaBean columnItem : columnsList) {
            String tablecolumnName = columnItem.getStr("TABLECOLUMN_NAME");
            String tablecolumnCode = columnItem.getStr("TABLECOLUMN_CODE").toUpperCase();
            columnMap.put(tablecolumnCode, tablecolumnName);
        }

        String tableCode = table.getStr("RESOURCETABLE_TABLECODE");
        List<DynaBean> columns = metaService.select("JE_CORE_TABLECOLUMN",
                ConditionsWrapper.builder().eq("TABLECOLUMN_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID")));

        //找到需要删除的列
        List<DynaBean> removedColumnList = null;
        for (DynaBean column : columns) {
            String columnCode = column.getStr("TABLECOLUMN_CODE", "").toUpperCase();
            boolean have = false;
            removedColumnList = Lists.newArrayList();
            for (DbModel dbModel : dbModels) {
                if (columnCode.equals(dbModel.getCode().toUpperCase())) {
                    have = true;
                    break;
                }
            }

            //不包含此列，则删除
            if (!have) {
                removedColumnList.add(column);
                metaTableColumnService.removeColumn(column, column.getStr("JE_CORE_TABLECOLUMN_ID"), isDdl);
            }
        }

        //设置主键
        String pkCode = table.getStr("RESOURCETABLE_PKCODE");
        if (StringUtil.isEmpty(pkCode)) {
            List<DynaBean> keys = metaService.select("JE_CORE_TABLEKEY",
                    ConditionsWrapper.builder().eq("TABLEKEY_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID")));
            for (DynaBean key : keys) {
                if ("Primary".equals(key.getStr("TABLEKEY_TYPE"))) {
                    pkCode = key.getStr("TABLEKEY_COLUMNCODE");
                }
            }
            if (StringUtil.isNotEmpty(pkCode)) {
                table.set("RESOURCETABLE_PKCODE", pkCode);
                metaService.update(table);
            }
        }

        //增加的字段集合
        List<DynaBean> addedColumnList = null;
        for (DbModel dbModel : dbModels) {
            boolean have = false;
            addedColumnList = Lists.newArrayList();

            for (DynaBean column : columns) {
                String columnCode = column.getStr("TABLECOLUMN_CODE", "").toUpperCase();
                if (columnCode.equals(dbModel.getCode().toUpperCase())) {
                    have = true;
                    boolean update = false;
                    if (!column.getStr("TABLECOLUMN_TYPE", "").equals(dbModel.getType())) {
                        update = true;
                        column.set("TABLECOLUMN_TYPE", dbModel.getType());
                    }
                    if (!column.getStr("TABLECOLUMN_LENGTH", "").equals(dbModel.getLength())) {
                        column.set("TABLECOLUMN_LENGTH", dbModel.getLength());
                        update = true;
                    }
                    if (!column.getStr("TABLECOLUMN_ISNULL", "").equals((dbModel.isNull() ? "1" : "0"))) {
                        column.set("TABLECOLUMN_ISNULL", dbModel.isNull() ? "1" : "0");
                        update = true;
                    }
                    if ("0".equals(column.getStr("TABLECOLUMN_ISCREATE"))) {
                        column.set("TABLECOLUMN_ISCREATE", "1");
                        update = true;
                    }
                    if (column.getStr("TABLECOLUMN_CODE", "").equals(table.getStr("RESOURCETABLE_PKCODE"))) {
                        column.set("TABLECOLUMN_TYPE", "ID");
                        update = true;
                    }
                    if (columnMap.containsKey(columnCode)) {
                        String columnName = columnMap.get(columnCode);
                        if(StringUtil.isNotEmpty(columnName)){
                            column.set("TABLECOLUMN_NAME",columnName);
                        }else if(StringUtil.isEmpty(column.getStr("TABLECOLUMN_NAME"))){
                            column.set("TABLECOLUMN_NAME",column.getStr("TABLECOLUMN_CODE"));
                        }
                        update = true;
                    }
                   /* if (!StringUtil.isEmpty(column.getStr("TABLECOLUMN_NAME"))) {
                        column.set("TABLECOLUMN_NAME", column.getStr("TABLECOLUMN_NAME"));
                        update = true;
                    } else {
                        column.set("TABLECOLUMN_NAME", column.getStr("TABLECOLUMN_CODE"));
                        update = true;
                    }*/
                    if (update) {
                        metaService.update(column);
                    }
                    continue;
                }
            }

            //现有元数据中没有此列，则把此列添加到元数据列表中
            if (!have) {
                DynaBean column = new DynaBean("JE_CORE_TABLECOLUMN", false);
                column.set(BeanService.KEY_PK_CODE, "JE_CORE_TABLECOLUMN_ID");
                column.set("TABLECOLUMN_CODE", dbModel.getCode());
                column.set("TABLECOLUMN_OLDCODE", dbModel.getCode());
                if (columnMap.containsKey(dbModel.getCode().toUpperCase())) {
                    String name = columnMap.get(dbModel.getCode().toUpperCase());
                    column.set("TABLECOLUMN_NAME", StringUtil.isEmpty(name) ? dbModel.getCode() : name);
                } else {
                    column.set("TABLECOLUMN_NAME", dbModel.getCode());
                }
                column.set("TABLECOLUMN_ISCREATE", "1");
                column.set("TABLECOLUMN_UNIQUE", "0");
                column.set("TABLECOLUMN_TREETYPE", "NORMAL");
                column.set("TABLECOLUMN_TABLECODE", tableCode);
                column.set("TABLECOLUMN_CLASSIFY", "PRO");
                column.set("SY_STATUS", "1");
                column.set("SY_ORDERINDEX", columns.size() + 1);
                column.set("TABLECOLUMN_ISNULL", dbModel.isNull() ? "1" : "0");
                column.set("TABLECOLUMN_TYPE", dbModel.getType());
                column.set("TABLECOLUMN_LENGTH", dbModel.getLength());
                column.set("TABLECOLUMN_TABLECODE", table.getStr("RESOURCETABLE_TABLECODE"));
                column.set("TABLECOLUMN_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID"));
                commonService.buildModelCreateInfo(column);
                if (column.getStr("TABLECOLUMN_CODE", "").equals(table.getStr("RESOURCETABLE_PKCODE"))) {
                    column.set("TABLECOLUMN_TYPE", "ID");
                }
                metaService.insert(column);
                columns.add(column);
                addedColumnList.add(column);
            }

        }

        //同步表格键
        syncTableFormKey(table, tableInfo);
        //同步表格索引
        syncTableTableIndex(table, tableInfo);
        developLogService.doDevelopLog("SYNC","同步表","TABLE","资源表",table.getStr("RESOURCETABLE_TABLENAME"), table.getStr("RESOURCETABLE_TABLECODE"),table.getStr("JE_CORE_RESOURCETABLE_ID"),table.getStr("SY_PRODUCT_ID"));
        return table;
    }

    private void syncTableFormKey(DynaBean table, DynaBean tableInfo) {
        List<DynaBean> keys = (List<DynaBean>) tableInfo.get(BeanService.KEY_TABLE_KEYS);
        List<DynaBean> metaKeys = metaService.select("JE_CORE_TABLEKEY", ConditionsWrapper.builder().
                eq("TABLEKEY_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID"))
                .ne("TABLEKEY_TYPE", "Unique"));
        for (DynaBean metaKey : metaKeys) {
            if (metaKey.getStr("TABLEKEY_TYPE").equals("Primary")) {
                continue;
            }
            String metaKeyCode = metaKey.getStr("TABLEKEY_CODE");
            Boolean exist = false;
            for (DynaBean key : keys) {
                String keyCode = key.getStr("TABLEKEY_CODE");
                if (metaKeyCode.equals(keyCode)) {
                    exist = true;
                    break;
                }
            }
            //元数据存在，数据库不存在，删除元数据
            if (!exist) {
                metaService.delete("JE_CORE_TABLEKEY", ConditionsWrapper.builder().eq(metaKey.getPkCode(), metaKey.getPkValue()));
            }
        }
        DynaBean metaInfo = new DynaBean();
        for (DynaBean key : keys) {
            if (key.get("TABLEKEY_TYPE").equals("Primary")) {
                continue;
            }
            String metaKeyCode = key.getStr("TABLEKEY_CODE");
            Boolean exist = false;
            for (DynaBean metaKey : metaKeys) {
                String keyCode = metaKey.getStr("TABLEKEY_CODE");
                if (metaKeyCode.equals(keyCode)) {
                    metaInfo = metaKey;
                    exist = true;
                    break;
                }
            }
            //数据库存在，元数据不存在，添加元数据
            if (!exist) {
                DynaBean dynaBean = new DynaBean("JE_CORE_TABLEKEY", false);
                dynaBean.setValues(key.getValues());
                dynaBean.setStr(BeanService.KEY_TABLE_CODE, "JE_CORE_TABLEKEY");
                dynaBean.set(BeanService.KEY_PK_CODE, "JE_CORE_TABLEKEY_ID");
                commonService.buildModelCreateInfo(dynaBean);
                dynaBean.setStr("TABLEKEY_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID"));
                dynaBean.setStr("TABLEKEY_CLASSIFY", "PRO");
                dynaBean.set("SY_ORDERINDEX", "0");
                metaService.insert(dynaBean);
            } else {
                DynaBean dynaBean = new DynaBean("JE_CORE_TABLEKEY", false);
                dynaBean.setValues(key.getValues());
                dynaBean.setStr(BeanService.KEY_TABLE_CODE, "JE_CORE_TABLEKEY");
                dynaBean.set(BeanService.KEY_PK_CODE, "JE_CORE_TABLEKEY_ID");
                commonService.buildModelCreateInfo(dynaBean);
                dynaBean.setStr("TABLEKEY_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID"));
                dynaBean.setStr(dynaBean.getPkCode(), metaInfo.getPkValue());
                dynaBean.setStr("TABLEINDEX_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID"));
                dynaBean.set("SY_ORDERINDEX", metaInfo.getStr("SY_ORDERINDEX"));
                dynaBean.setStr("TABLEKEY_CLASSIFY", metaInfo.getStr("TABLEKEY_CLASSIFY"));
                metaService.update(dynaBean);
            }
        }


    }

    private void syncTableTableIndex(DynaBean table, DynaBean tableInfo) {
        List<DynaBean> indexs = (List<DynaBean>) tableInfo.get(BeanService.KEY_TABLE_INDEXS);
        List<DynaBean> metaIndexs = metaService.select("JE_CORE_TABLEINDEX", ConditionsWrapper.builder().
                eq("TABLEINDEX_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID")));
        for (DynaBean metaIndex : metaIndexs) {
            String metaKeyCode = metaIndex.getStr("TABLEINDEX_NAME");
            Boolean exist = false;
            for (DynaBean index : indexs) {
                String keyCode = index.getStr("TABLEINDEX_NAME");
                if (metaKeyCode.equals(keyCode)) {
                    exist = true;
                    break;
                }
            }
            //元数据存在，数据库不存在，删除元数据
            if (!exist) {
                metaService.delete("JE_CORE_TABLEINDEX", ConditionsWrapper.builder().eq(metaIndex.getPkCode(), metaIndex.getPkValue()));
            }
        }

        for (DynaBean index : indexs) {
            if (index.getStr("TABLEINDEX_FIELDNAME").equals("主键ID")) {
                continue;
            }
            String indexCode = index.getStr("TABLEINDEX_NAME");
            Boolean exist = false;
            DynaBean metaInfo = new DynaBean();
            for (DynaBean metaIndex : metaIndexs) {
                String keyCode = metaIndex.getStr("TABLEINDEX_NAME");
                if (indexCode.equals(keyCode)) {
                    metaInfo = metaIndex;
                    exist = true;
                    break;
                }
            }
            //数据库存在，元数据不存在，添加元数据
            if (!exist) {
                DynaBean dynaBean = new DynaBean("JE_CORE_TABLEINDEX", false);
                dynaBean.setValues(index.getValues());
                dynaBean.set(BeanService.KEY_PK_CODE, "JE_CORE_TABLEINDEX_ID");
                dynaBean.setStr(BeanService.KEY_TABLE_CODE, "JE_CORE_TABLEINDEX");
                commonService.buildModelCreateInfo(dynaBean);
                dynaBean.setStr("TABLEINDEX_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID"));
                dynaBean.set("SY_ORDERINDEX", 0);
                metaService.insert(dynaBean);
            } else {
                DynaBean dynaBean = new DynaBean("JE_CORE_TABLEINDEX", false);
                dynaBean.setValues(index.getValues());
                dynaBean.set(BeanService.KEY_PK_CODE, "JE_CORE_TABLEINDEX_ID");
                dynaBean.setStr(BeanService.KEY_TABLE_CODE, "JE_CORE_TABLEINDEX");
                commonService.buildModelModifyInfo(dynaBean);
                dynaBean.setStr(dynaBean.getPkCode(), metaInfo.getPkValue());
                dynaBean.setStr("TABLEINDEX_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID"));
                dynaBean.set("SY_ORDERINDEX", metaInfo.getStr("SY_ORDERINDEX"));
                metaService.update(dynaBean);
            }
        }


    }

    /**
     * RESOURCETABLE_IMPORT 是否是导入的表，1：是；0：不是
     *
     * @param dynaBean
     * @return
     */
    @Override
    @Transactional
    public DynaBean doSave(DynaBean dynaBean) {
        String parentId = dynaBean.getStr("SY_PARENT");
        String moreroot = dynaBean.getStr("RESOURCETABLE_MOREROOT");
        if (!parentId.equals("ROOT")) {
            DynaBean pareentTable = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", parentId);
            String syProductId = pareentTable.getStr("SY_PRODUCT_ID");
            productRpcService.buildDynaBeanProductInfo(dynaBean, syProductId);
        }
        String uuid = JEUUID.uuid();
        dynaBean.set("SY_PARENT", parentId);
        dynaBean.setStr("JE_CORE_RESOURCETABLE_ID", uuid);
        /*if (StringUtil.isNotEmpty(dynaBean.getStr("SY_PATH"))) {
            dynaBean.set("SY_PATH", dynaBean.getStr("SY_PATH") + "/" + uuid);
        }*/
        commonService.buildResourceTable(dynaBean);
        commonService.buildModelCreateInfo(dynaBean);
        dynaBean.set("SY_JECORE", "0");
        dynaBean.set("SY_JESYS", "0");
        dynaBean.set("RESOURCETABLE_PKCODE", dynaBean.get("RESOURCETABLE_TABLECODE") + "_ID");
        dynaBean.set("RESOURCETABLE_IMPORT", "0");
        dynaBean.table("JE_CORE_RESOURCETABLE");
        dynaBean.set("RESOURCETABLE_MOREROOT", moreroot);
        String RESOURCETABLE_TYPE = dynaBean.getStr("RESOURCETABLE_TYPE");
        String RESOURCETABLE_ICON = dynaBean.getStr("RESOURCETABLE_ICON");
        if(StringUtil.isEmpty(RESOURCETABLE_ICON)){
            if("PT".equals(RESOURCETABLE_TYPE)){
                RESOURCETABLE_ICON="jeicon jeicon-table";
            }
            if("TREE".equals(RESOURCETABLE_TYPE)){
                RESOURCETABLE_ICON="jeicon jeicon-treetable";
            }
            dynaBean.set("RESOURCETABLE_ICON", RESOURCETABLE_ICON);
        }
        if ("MODULE".equals(RESOURCETABLE_TYPE)) {
            dynaBean.setStr("RESOURCETABLE_ISCREATE", "1");
        }
        metaService.insert(dynaBean);
        Boolean isTree = false;
        if (TableType.TREETABLE.equals(dynaBean.getStr("RESOURCETABLE_TYPE"))) {
            isTree = true;
        }
        if(!"MODULE".equals(RESOURCETABLE_TYPE)){
            metaTableColumnService.initColumns(dynaBean, isTree);
            metaTableKeyService.initKeys(dynaBean, isTree);
            metaTableIndexService.initIndexs(dynaBean, isTree);
        }
        developLogService.doDevelopLog("CREATE", "创建", "TABLE", "资源表", dynaBean.getStr("RESOURCETABLE_TABLENAME"), dynaBean.getStr("RESOURCETABLE_TABLECODE"), dynaBean.getStr("JE_CORE_RESOURCETABLE_ID"),dynaBean.getStr("SY_PRODUCT_ID"));
        return dynaBean;
    }

    /**
     * 同步外键图标样式
     */
    @Transactional
    public void updateTableKey(DynaBean resourceTable, List<DynaBean> keys) {
        String tableCode = resourceTable.getStr("RESOURCETABLE_TABLECODE");
        List<String> parentTableCodes = new ArrayList<String>();
        for (DynaBean key : keys) {
            if ("Foreign".equals(key.get("TABLEKEY_TYPE"))) {
                parentTableCodes.add(key.getStr("TABLEKEY_LINKTABLE"));
            } else if ("Primary".equals(key.getStr("TABLEKEY_TYPE"))) {
                resourceTable.set("RESOURCETABLE_PKCODE", key.getStr("TABLEKEY_COLUMNCODE"));
            }
        }
        String oldParentTaleCodes = resourceTable.getStr("RESOURCETABLE_PARENTTABLECODES", "");
        List<String> oldParentTables = new ArrayList<String>();
        for (String oldParent : oldParentTaleCodes.split(",")) {
            if (StringUtil.isNotEmpty(oldParent)) {
                oldParentTables.add(oldParent);
            }
        }
        //设置其用到了外键
        for (String tC : parentTableCodes) {
            if (!oldParentTables.contains(tC)) {
                oldParentTables.add(tC);
            }
        }
        //更新父表关联信息
        for (String parentTableCode : oldParentTables) {
            DynaBean fatherTable = metaService.selectOne("JE_CORE_RESOURCETABLE",
                    ConditionsWrapper.builder().eq("RESOURCETABLE_TABLECODE", parentTableCode));
            //TODO 如果为null，则让父表创建资源表，让父表先导入

            //如果存在外键
            String childTableCodes = fatherTable.getStr("RESOURCETABLE_CHILDTABLECODES", "");
            String childParentTables = fatherTable.getStr("RESOURCETABLE_PARENTTABLECODES", "");
            if (parentTableCodes.contains(parentTableCode)) {
                if (StringUtil.isNotEmpty(childTableCodes)) {
//						//不是空的操作
                    if (childTableCodes.indexOf(tableCode) == -1) {
                        childTableCodes = childTableCodes + "," + tableCode;
                    }
                    fatherTable.set("RESOURCETABLE_CHILDTABLECODES", childTableCodes);
                } else {
                    fatherTable.set("RESOURCETABLE_CHILDTABLECODES", tableCode);
                }
            } else {
                List<String> parentChildCodes = new ArrayList<String>();
                for (String childCode : childTableCodes.split(",")) {
                    if (StringUtil.isNotEmpty(childCode)) {
                        parentChildCodes.add(childCode);
                    }
                }
                parentChildCodes.remove(tableCode);
                fatherTable.set("RESOURCETABLE_CHILDTABLECODES", StringUtil.buildSplitString(ArrayUtils.getArray(parentChildCodes), ","));
            }
            metaService.update(fatherTable);
        }
        resourceTable.set("RESOURCETABLE_PARENTTABLECODES", StringUtil.buildSplitString(ArrayUtils.getArray(parentTableCodes), ","));
        if (parentTableCodes.size() > 0) {
            resourceTable.set("RESOURCETABLE_ISUSEFOREIGNKEY", "1");
        }
        resourceTable.set(BeanService.KEY_TABLE_CODE, "JE_CORE_RESOURCETABLE");
        metaService.update(resourceTable);
    }

    @Override
    @Transactional
    public DynaBean doUpdate(DynaBean dynaBean) {
        DynaBean oldTable = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", dynaBean.getStr("JE_CORE_RESOURCETABLE_ID"));
        if (!dynaBean.get("RESOURCETABLE_TABLECODE").equals(oldTable.get("RESOURCETABLE_TABLECODE"))) {
            metaService.executeSql("UPDATE JE_CORE_TABLECOLUMN SET TABLECOLUMN_TABLECODE={0} WHERE TABLECOLUMN_RESOURCETABLE_ID={1}", dynaBean.getStr("JE_CORE_RESOURCETABLE_ID"), dynaBean.getStr("JE_CORE_RESOURCETABLE_ID"));
            metaService.executeSql("UPDATE JE_CORE_TABLEKEY SET TABLEKEY_TABLECODE={0} WHERE TABLEKEY_RESOURCETABLE_ID={1}", dynaBean.getStr("RESOURCETABLE_TABLECODE"), dynaBean.getStr("JE_CORE_RESOURCETABLE_ID"));
        }
        commonService.buildModelModifyInfo(dynaBean);
        metaService.update(dynaBean);
        metaTableTraceService.saveTableTrace("JE_CORE_RESOURCETABLE", oldTable, dynaBean, "UPDATE", dynaBean.getStr("JE_CORE_RESOURCETABLE_ID"), dynaBean.getStr("RESOURCETABLE_ISCREATE"));
        developLogService.doDevelopLog("UPDATE", "修改", "TABLE", "资源表", dynaBean.getStr("RESOURCETABLE_TABLENAME"), dynaBean.getStr("RESOURCETABLE_TABLECODE"), dynaBean.getStr("JE_CORE_RESOURCETABLE_ID"),dynaBean.getStr("SY_PRODUCT_ID"));
        return dynaBean;
    }

    @Override
    @Transactional
    public DynaBean copyTable(DynaBean dynaBean) {

        String pkValue = dynaBean.getStr("JE_CORE_RESOURCETABLE_ID");
        DynaBean oldTable = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", pkValue);
        if (oldTable == null) {
            return null;
        }

        oldTable.set("RESOURCETABLE_ISCREATE", "0");
        oldTable.set("RESOURCETABLE_TABLECODE", dynaBean.getStr("RESOURCETABLE_TABLECODE"));
        oldTable.set("RESOURCETABLE_TABLENAME", oldTable.getStr("RESOURCETABLE_TABLENAME") + "(复制)");

        if (StringUtil.isNotEmpty(oldTable.getStr("SY_PATH"))) {
            String uuid = JEUUID.uuid();
            oldTable.setStr(dynaBean.getStr(BeanService.KEY_PK_CODE), uuid);
            oldTable.set("SY_PATH", oldTable.getStr("SY_PATH").substring(0, oldTable.getStr("SY_PATH").lastIndexOf("/") + 1) + "/" + uuid);
        }

        DynaBean newTable = commonService.doSave(oldTable);
        List<DynaBean> columns = metaService.select("JE_CORE_TABLECOLUMN", ConditionsWrapper.builder().eq("TABLECOLUMN_RESOURCETABLE_ID", pkValue));
        List<DynaBean> keys = metaService.select("JE_CORE_TABLEKEY", ConditionsWrapper.builder().eq("TABLEKEY_RESOURCETABLE_ID", pkValue));
        List<DynaBean> indexs = metaService.select("JE_CORE_TABLEINDEX", ConditionsWrapper.builder().eq("TABLEINDEX_RESOURCETABLE_ID", pkValue));

        for (DynaBean column : columns) {
            column.set("JE_CORE_TABLECOLUMN_ID", null);
            column.set("TABLECOLUMN_ISCREATE", "0");
            column.set("TABLECOLUMN_TABLECODE", newTable.getStr("RESOURCETABLE_TABLECODE"));
            column.set("TABLECOLUMN_RESOURCETABLE_ID", newTable.getStr("JE_CORE_RESOURCETABLE_ID"));
            metaService.insert(column);
        }

        for (DynaBean key : keys) {
            key.set("JE_CORE_TABLEKEY_ID", null);
            if ("Inline".equals(key.getStr("TABLEKEY_TYPE"))) {
                key.set("TABLEKEY_CODE", "JE_" + DateUtils.getUniqueTime() + "_PARENT");
            } else if ("Primary".equals(key.getStr("TABLEKEY_TYPE"))) {
                key.set("TABLEKEY_CODE", key.getStr("TABLEKEY_CODE").replace(oldTable.getStr("RESOURCETABLE_TABLECODE"), newTable.getStr("RESOURCETABLE_TABLECODE")));
            } else {
                key.set("TABLEKEY_CODE", "JE_" + DateUtils.getUniqueTime());
            }
            key.set("TABLEKEY_ISCREATE", "0");
            key.set("TABLEKEY_TABLECODE", newTable.getStr("RESOURCETABLE_TABLECODE"));
            key.set("TABLEKEY_RESOURCETABLE_ID", newTable.getStr("JE_CORE_RESOURCETABLE_ID"));
            metaService.insert(key);
        }

        for (DynaBean index : indexs) {
            if ((oldTable.getStr("RESOURCETABLE_TABLECODE") + "_ID").equals(index.getStr("TABLEINDEX_FIELDCODE"))) {
                index.set("TABLEINDEX_NAME", index.getStr("TABLEINDEX_NAME").replace(oldTable.getStr("RESOURCETABLE_TABLECODE"), newTable.getStr("RESOURCETABLE_TABLECODE")));
                index.set("TABLEINDEX_FIELDCODE", newTable.getStr("RESOURCETABLE_PKCODE"));
            } else if ("SY_ORDERINDEX".equals(index.getStr("TABLEINDEX_FIELDCODE"))) {
                index.set("TABLEINDEX_NAME", index.getStr("TABLEINDEX_NAME").replace(oldTable.getStr("RESOURCETABLE_TABLECODE"), newTable.getStr("RESOURCETABLE_TABLECODE")));
                index.set("TABLEINDEX_FIELDCODE", "SY_ORDERINDEX");
            } else {
                index.set("TABLEINDEX_NAME", "JE_" + DateUtils.getUniqueTime());
                String columnCode = index.getStr("TABLEINDEX_FIELDCODE");
                index.set("TABLEINDEX_FIELDCODE", columnCode);
            }
        }
        return newTable;
    }


    @Override
    @Transactional
    public DynaBean pasteTable(String newTableName, String newTableCode, DynaBean dynaBean, String useNewName) {
        Boolean useNew = false;
        if ("1".equals(useNewName)) {
            useNew = true;
        }
        DynaBean parentTable = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", dynaBean.getStr("SY_PARENT"));
        DynaBean sourceTable = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", dynaBean.getStr("JE_CORE_RESOURCETABLE_ID"));
        String oldTableCode = sourceTable.getStr("RESOURCETABLE_TABLECODE");
        String oldPkName = sourceTable.getStr("RESOURCETABLE_PKCODE");
        String newPkName = newTableCode + "_ID";
        if (StringUtil.isNotEmpty(parentTable.getStr("SY_PATH"))) {
            String uuid = JEUUID.uuid();
            sourceTable.setStr("JE_CORE_RESOURCETABLE_ID", uuid);
            sourceTable.set("SY_PATH", parentTable.getStr("SY_PATH"));
            sourceTable.set("SY_PARENT", parentTable.getPkValue());
            sourceTable.set("SY_NODETYPE", dynaBean.get("SY_NODETYPE"));
            sourceTable.set("SY_LAYER", parentTable.getInt("SY_LAYER") + 1);
            sourceTable.set("SY_DISABLED", 0);
        }
        sourceTable.set("RESOURCETABLE_ISCREATE", "0");
        sourceTable.set("RESOURCETABLE_TABLENAME", newTableName);
        sourceTable.set("RESOURCETABLE_TABLECODE", newTableCode);
        sourceTable.set("RESOURCETABLE_PKCODE", newPkName);
        if (!"TREE".equals(sourceTable.getStr("RESOURCETABLE_ICON"))) {
            sourceTable.set("RESOURCETABLE_ICON", "jeicon jeicon-table");
        }
        sourceTable.set("RESOURCETABLE_CHILDTABLECODES", "");
        sourceTable.set("RESOURCETABLE_ISUSEFOREIGNKEY", "0");
        sourceTable.set("RESOURCETABLE_OLDTABLECODE", "");
        sourceTable.set("RESOURCETABLE_PARENTTABLECODES", "");
        sourceTable.set("RESOURCETABLE_USEFUNC", "");
        sourceTable.set(BeanService.KEY_TABLE_CODE, "JE_CORE_RESOURCETABLE");
        DynaBean pasted = commonService.doSave(sourceTable);

        String oldTablePre = oldTableCode;
        // TODO
        if (oldTableCode.lastIndexOf("_") != -1) {
            if (oldTableCode.lastIndexOf("_") == oldTableCode.length() - 1) {
                oldTablePre = "";
            } else {
                oldTablePre = oldTableCode.substring(oldTableCode.lastIndexOf("_") + 1);
            }
        }
        String newTablePre = newTableCode;
        if (newTableCode.lastIndexOf("_") != -1) {
            if (newTableCode.lastIndexOf("_") == newTableCode.length() - 1) {
                newTablePre = "";
            } else {
                newTablePre = newTableCode.substring(newTableCode.lastIndexOf("_") + 1);
            }
        }
        insertTableColumn(dynaBean, pasted, useNew, oldPkName, newPkName, newTablePre, oldTablePre);
        insertTableKeys(dynaBean, pasted, useNew, newTableCode, oldTableCode, newPkName, newTablePre, oldTablePre);
        insertTableIndexs(dynaBean, pasted, useNew, oldPkName, newPkName, newTablePre, oldTablePre);
        developLogService.doDevelopLog("COPY", "粘贴", "TABLE", "资源表", pasted.getStr("RESOURCETABLE_TABLENAME"), pasted.getStr("RESOURCETABLE_TABLECODE"), pasted.getStr("JE_CORE_RESOURCETABLE_ID"),pasted.getStr("SY_PRODUCT_ID"));
        return sourceTable;
    }

    private void insertTableIndexs(DynaBean dynaBean, DynaBean pasted, Boolean useNew, String oldPkName, String newPkName, String newTablePre, String oldTablePre) {
        List<DynaBean> indexs = metaService.select("JE_CORE_TABLEINDEX",
                ConditionsWrapper.builder().eq("TABLEINDEX_RESOURCETABLE_ID", dynaBean.getStr("JE_CORE_RESOURCETABLE_ID")));

        for (Integer i = 0; i < indexs.size(); i++) {
            DynaBean index = indexs.get(i);
            if (oldPkName.equals(index.getStr("TABLEINDEX_FIELDCODE"))) {
                index.set("TABLEINDEX_NAME", "JE_" + DateUtils.getUniqueTime() + "_ID");
                index.set("TABLEINDEX_FIELDCODE", newPkName);
            } else if ("SY_ORDERINDEX".equals(index.getStr("TABLEINDEX_FIELDCODE"))) {
                index.set("TABLEINDEX_NAME", "JE_" + DateUtils.getUniqueTime() + "_ORDER");
                index.set("TABLEINDEX_FIELDCODE", "SY_ORDERINDEX");
            } else {
                index.set("TABLEINDEX_NAME", "JE_" + DateUtils.getUniqueTime());
                if (useNew) {
                    String columnCode = index.getStr("TABLEINDEX_FIELDCODE");
                    if (columnCode.startsWith(oldTablePre + "_")) {
                        columnCode = newTablePre + columnCode.substring(columnCode.indexOf("_"));
                    }
                    index.set("TABLEINDEX_FIELDCODE", columnCode);
                }
            }
            index.set("TABLEINDEX_ISCREATE", "0");
            index.set("JE_CORE_TABLEINDEX_ID", null);
            index.set("TABLEINDEX_RESOURCETABLE_ID", pasted.getStr("JE_CORE_RESOURCETABLE_ID"));
            index.set("TABLEINDEX_TABLECODE", pasted.getStr("RESOURCETABLE_TABLECODE"));
            index.set(BeanService.KEY_TABLE_CODE, "JE_CORE_TABLEINDEX");
            metaService.insert(index);
        }
    }

    private void insertTableKeys(DynaBean dynaBean, DynaBean pasted, Boolean useNew, String newTableCode, String oldTableCode, String newPkName, String newTablePre, String oldTablePre) {
        List<DynaBean> keys = metaService.select("JE_CORE_TABLEKEY",
                ConditionsWrapper.builder().eq("TABLEKEY_RESOURCETABLE_ID", dynaBean.getStr("JE_CORE_RESOURCETABLE_ID")));

        for (Integer i = 0; i < keys.size(); i++) {
            DynaBean key = keys.get(i);
            if ("Inline".equals(key.getStr("TABLEKEY_TYPE")) || "Primary".equals(key.getStr("TABLEKEY_TYPE"))) {
                if ("Inline".equals(key.getStr("TABLEKEY_TYPE"))) {
                    key.set("TABLEKEY_CODE", "JE_" + DateUtils.getUniqueTime() + "_PARENT");
                    key.set("TABLEKEY_LINKTABLE", newTableCode);
                    key.set("TABLEKEY_LINECOLUMNCODE", newPkName);
                } else {
                    key.set("TABLEKEY_CODE", key.getStr("TABLEKEY_CODE").replace(oldTableCode, newTableCode));
                    key.set("TABLEKEY_COLUMNCODE", newPkName);
                }
            } else {
                key.set("TABLEKEY_CODE", "JE_" + DateUtils.getUniqueTime());
                if (useNew) {
                    String columnCode = key.getStr("TABLEKEY_COLUMNCODE");
                    if (columnCode.startsWith(oldTablePre + "_")) {
                        columnCode = newTablePre + columnCode.substring(columnCode.indexOf("_"));
                    }
                    key.set("TABLEKEY_COLUMNCODE", columnCode);
                }
            }
            key.set("TABLEKEY_ISCREATE", "0");
            key.set("JE_CORE_TABLEKEY_ID", null);
            key.set("TABLEKEY_RESOURCETABLE_ID", pasted.getStr("JE_CORE_RESOURCETABLE_ID"));
            key.set("TABLEKEY_TABLECODE", pasted.getStr("RESOURCETABLE_TABLECODE"));
            key.set(BeanService.KEY_TABLE_CODE, "JE_CORE_TABLEKEY");
            metaService.insert(key);
        }

    }

    private void insertTableColumn(DynaBean dynaBean, DynaBean pasted, Boolean useNew, String oldPkName, String newPkName, String newTablePre, String oldTablePre) {
        List<DynaBean> columns = metaService.select("JE_CORE_TABLECOLUMN",
                ConditionsWrapper.builder().eq("TABLECOLUMN_RESOURCETABLE_ID", dynaBean.getStr("JE_CORE_RESOURCETABLE_ID")));

        for (DynaBean column : columns) {
            //主键使用新表主键
            if (oldPkName.equals(column.getStr("TABLECOLUMN_CODE"))) {
                column.set("TABLECOLUMN_CODE", newPkName);
            } else {
                if (useNew) {
                    String columnCode = column.getStr("TABLECOLUMN_CODE");
                    if (columnCode.startsWith(oldTablePre + "_")) {
                        columnCode = newTablePre + columnCode.substring(columnCode.indexOf("_"));
                    }
                    column.set("TABLECOLUMN_CODE", columnCode);
                }
            }
            column.set("TABLECOLUMN_RESOURCETABLE_ID", pasted.getStr("JE_CORE_RESOURCETABLE_ID"));
            column.set("TABLECOLUMN_TABLECODE", pasted.getStr("RESOURCETABLE_TABLECODE"));
            column.set("TABLECOLUMN_ISCREATE", "0");
            column.set(BeanService.KEY_TABLE_CODE, "JE_CORE_TABLECOLUMN");
            column.set("JE_CORE_TABLECOLUMN_ID", null);
            metaService.insert(column);
        }
    }


    @Override
    @Transactional
    public DynaBean tableMove(DynaBean dynaBean, String oldParentId) {
        DynaBean table = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", dynaBean.getStr("JE_CORE_RESOURCETABLE_ID"));
        String newParentId = dynaBean.getStr("SY_PARENT");
        String oldPath = table.getStr("SY_PATH");
        table.set("SY_PATH", dynaBean.getStr("SY_PATH") + "/" + dynaBean.getStr("JE_CORE_RESOURCETABLE_ID"));
        table.set("SY_PARENT", newParentId);
        Integer chaLayer = dynaBean.getInt("SY_LAYER", 0) - table.getInt("SY_LAYER", 0);
        table.set("SY_LAYER", dynaBean.get("SY_LAYER"));
        table.set(BeanService.KEY_TABLE_CODE, "JE_CORE_RESOURCETABLE");
        //更新当前节点下所有孩子的路径信息
        metaService.executeSql("UPDATE JE_CORE_RESOURCETABLE SET SY_PATH=REPLACE(SY_PATH,'" + oldPath + "','" + table.getStr("SY_PATH") + "'),SY_LAYER=(SY_LAYER+" + chaLayer + ") WHERE SY_PATH LIKE '%" + oldPath + "%' AND JE_CORE_RESOURCETABLE_ID!='" + dynaBean.getStr("JE_CORE_RESOURCETABLE_ID") + "'");
        metaService.update(table);
        commonService.updateTreePanent4NodeType("JE_CORE_RESOURCETABLE", oldParentId);
        commonService.updateTreePanent4NodeType("JE_CORE_RESOURCETABLE", newParentId);
        //更新权限的模块编码，为了节省授权的性能
        return table;
    }

    /**
     * DDL加载
     *
     * @param tableId 表信息
     * @param type    表类型
     * @return
     */
    @Override
    public String generateSql(String tableId, String type) {
        StringBuffer sql = new StringBuffer();
        StringBuffer alertSql = new StringBuffer();
        DynaBean table = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", tableId);
        if (null == table) {
            throw new PlatformException("获取资源表信息异常，请查看是否存在此表！", PlatformExceptionEnum.JE_CORE_TABLE_ERROR);
        }
        if ("0".equals(table.getStr("RESOURCETABLE_ISCREATE"))) {
            return "";
        }
        table = metaBeanService.getResourceTable(table.getStr("RESOURCETABLE_TABLECODE"));
        String tableCode = table.getStr("RESOURCETABLE_TABLECODE");
        String tableType = table.getStr("RESOURCETABLE_TYPE");
        if (tableType.equals(TableType.PTTABLE) || tableType.equals(TableType.TREETABLE)) {
            sql.append("-- " + table.getStr("RESOURCETABLE_TABLENAME") + "(" + table.getStr("RESOURCETABLE_TABLECODE") + ") 表结构的创建语句\n ");
            List<String> arraySql = BuildingSqlFactory.build().getDDL4CreateTable(table);
            for (String cSql : arraySql) {
                if (cSql.toUpperCase().startsWith("CREATE TABLE")) {
                    sql.append(cSql + ";\n");
                }else {
                    alertSql.append(cSql + ";\n");
                }
            }
            try {
                return ParseBuildingSqlFactory.build().beautifyCreateTableDdl(sql.toString()) + "\n" +
                        alertSql.toString();
            } catch (SQLSyntaxErrorException throwables) {
                throwables.printStackTrace();
            }
        } else if ("DATA".equals(type)) {
            sql.append("-- " + table.getStr("RESOURCETABLE_TABLENAME") + "(" + table.getStr("RESOURCETABLE_TABLECODE") + ")表数据插入SQL");
            List<DynaBean> datas = metaService.select(ConditionsWrapper.builder().table(tableCode));
            Set<String> numberFields = new HashSet<String>();
            for (DynaBean column : (List<DynaBean>) table.get(BeanService.KEY_TABLE_COLUMNS)) {
                String fieldType = column.getStr("TABLECOLUMN_TYPE");
                String length = column.getStr("TABLECOLUMN_LENGTH", "").toUpperCase();
                if (ColumnType.FLOAT.equals(fieldType)
                        || ColumnType.NUMBER.equals(fieldType)
                        || (ColumnType.CUSTOM.equals(fieldType) && (length.indexOf("FLOAT") != -1))
                        || (ColumnType.CUSTOM.equals(fieldType) && (length.indexOf("NUMBER") != -1))
                ) {
                    numberFields.add(column.getStr("TABLECOLUMN_CODE"));
                }
            }
            for (DynaBean bean : datas) {
                StringBuilder insertSql = new StringBuilder();
                String fieldNames = metaBeanService.getNames4Sql(table);
                StringBuilder values = new StringBuilder();
                //根据ResourceTable得到DyanBean
                DynaBean dynaBean = metaBeanService.getDynaBeanByResourceTable(table);
                String[] arrayName = metaBeanService.getNames(dynaBean);
                for (String name : arrayName) {
                    if (!name.startsWith(StringUtil.DOLLAR)) {
                        if (bean.get(name) == null) {
                            values.append("NULL,");
                        } else if (numberFields.contains(name)) {
                            values.append("" + bean.get(name) + ",");
                        } else {
                            values.append("'" + bean.get(name) + "',");
                        }
                    }
                }
                values.setLength(values.length() - 1);
                insertSql.append("INSERT INTO " + tableCode + "(" + fieldNames + ") VALUES (" + values + ");");
                sql.append(insertSql);
            }
            return "";
        }
        return "";
    }

    /**
     * 更新树形表数据(路径 层次 顺序 排序字段)
     *
     * @param tableCode 表编码
     * @param pkCode    主键code
     * @param preFix    字段前缀
     */
    @Override
    @Transactional
    public void syncTreePath(String tableCode, String pkCode, String preFix) {
        syncPath(tableCode, pkCode, preFix, "ROOT");
    }

    private void syncPath(String tableCode, String pkCode, String preFix, String parentId) {
        String parentField = preFix + "PARENT";
        String pathField = preFix + "PATH";
        String parentPathField = preFix + "PARENTPATH";
        String treeOrderField = preFix + "TREEORDERINDEX";
        String layerField = preFix + "LAYER";
        String nodeTypeField = preFix + "NODETYPE";
        String orderField = preFix + "ORDERINDEX";
        String[] fields = new String[]{pkCode, parentField, pathField, parentPathField, treeOrderField, layerField, nodeTypeField, orderField};
        String querySql = " SELECT " + StringUtil.buildSplitString(fields, ",") + " FROM " + tableCode + " WHERE " + parentField + "='" + parentId + "' ORDER BY " + orderField;
        if (NodeType.ROOT.equalsIgnoreCase(parentId)) {
            metaService.executeSql(" UPDATE " + tableCode + " SET "
                    + nodeTypeField + "={0},"
                    + pathField + "={1},"
                    + layerField + "={2},"
                    + treeOrderField + "={3},"
                    + parentPathField + "='' WHERE "
                    + pkCode + "={4}", "ROOT", "/ROOT", "0", "000001", parentId);
        }

        List<Map<String, Object>> parentNodes = metaService.selectSql("SELECT " + StringUtil.buildSplitString(fields, ",") + " FROM " + tableCode + " WHERE " + pkCode + "={0}", parentId);
        if (parentNodes.isEmpty()) {
            return;
        }
        Map parent = parentNodes.get(0);
        List<Map<String, Object>> lists = metaService.selectSql(querySql);
        int index = 1;
        for (Map vals : lists) {
            metaService.executeSql("UPDATE " + tableCode + " SET "
                            + nodeTypeField + "={0},"
                            + pathField + "={1},"
                            + layerField + "={2},"
                            + treeOrderField + "={3},"
                            + parentPathField + "={4} WHERE "
                            + pkCode + "={5}",
                    NodeType.LEAF,
                    (parent.get(pathField) + "/" + vals.get(pkCode)),
                    (Integer.parseInt(parent.get(layerField) + "") + 1),
                    (parent.get(treeOrderField) + StringUtil.preFillUp(index + "", 6, '0')),
                    parent.get(pathField),
                    vals.get(pkCode));
            index++;
            String id = vals.get(pkCode) + "";
            syncPath(tableCode, pkCode, preFix, id);
        }
        if (lists.size() > 0 && !NodeType.ROOT.equalsIgnoreCase(parentId)) {
            metaService.executeSql(" UPDATE " + tableCode + " SET "
                    + nodeTypeField + "={0} WHERE " + pkCode + "={1}", NodeType.GENERAL, parentId);
        }
    }

    /**
     * 查询sql列表
     *
     * @param columnList
     * @param whereList
     * @param orderList
     * @return
     */
    @Override
    public List<Map<String, Object>> selectSqlTable(JSONArray columnList, JSONArray whereList, JSONArray orderList, String tableCode, String page) {
        StringBuilder sql = generationSelectSql(columnList, tableCode, whereList, orderList);
        if(StringUtil.isNotEmpty(page)){
            if ("-1".equals(page)) {
                page = "30";
            }
            sql.append(" LIMIT 0," + page);
        }
        List<Map<String, Object>> list = metaService.selectSql(sql.toString());
        return list;
    }


    /**
     * 查询sql的总条数
     *
     * @param whereList
     * @param orderList
     * @param tableCode
     * @return
     */
    @Override
    public long selectSqlTableByTotal(JSONArray whereList, JSONArray orderList, String tableCode) {
        StringBuilder sql = generationSelectSqlByTatal(tableCode, whereList, orderList);
        List<Map<String,Object>> list = metaService.selectSql(sql.toString());
        return list.size();
    }

    @Override
    public DynaBean saveFuncAndMenu(DynaBean dynaBean) {
        String id = JEUUID.uuid();

        /**
         * 创建功能
         */
        DynaBean tableInfo = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", dynaBean.getStr("JE_CORE_RESOURCETABLE_ID"));
        dynaBean.set("JE_CORE_FUNCINFO_ID", id);
        dynaBean.setStr("FUNCINFO_TABLENAME", tableInfo.getStr("RESOURCETABLE_TABLECODE"));
        dynaBean.setStr("SY_PARENT", dynaBean.getStr("FUNCINFO_SY_PARENT"));
        dynaBean.setStr("FUNCINFO_NODEINFOTYPE", "FUNC");
        dynaBean.setStr("SY_STATUS", "1");
        dynaBean.setStr("FUNCINFO_ICON", "jeicon jeicon-function");
        String resourcetableType = tableInfo.getStr("RESOURCETABLE_TYPE");
        String functype = "";
        if ("PT".equals(resourcetableType)) {
            functype = "FUNC";
        }
        if ("TREE".equals(resourcetableType)) {
            functype = "TREE";
        }
        if ("VIEW".equals(resourcetableType)) {
            functype = "VIEW";
        }
        dynaBean.setStr("FUNCINFO_FUNCTYPE", functype);
        funcInfoService.doSave(dynaBean);
        metaRbacService.clearMyBatisCache();
        /**
         * 创建菜单
         */

        String createMenu = dynaBean.getStr("CREATE_MENU");
        DynaBean product = metaService.selectOneByPk("JE_PRODUCT_MANAGE",dynaBean.getStr("SY_PRODUCT_ID"));
        DynaBean menu = new DynaBean("JE_CORE_MENU", true);
        if ("1".equals(createMenu)) {
            menu.setStr("MENU_MENUNAME", dynaBean.getStr("MENU_MENUNAME"));
            menu.setStr("MENU_BADGETYPE", dynaBean.getStr("sql"));
            menu.setStr("MENU_NODEINFO", dynaBean.getStr("FUNCINFO_FUNCCODE"));
            menu.setStr("MENU_BADGELOAD", "load");
            menu.setStr("SY_PARENT", dynaBean.getStr("MENU_SY_PARENT"));
            menu.setStr("MENU_NODEINFOTYPE", "MT");
            menu.setStr("SY_PRODUCT_ID", dynaBean.getStr("SY_PRODUCT_ID"));
            menu.setStr("SY_PRODUCT_CODE",product.getStr("PRODUCT_CODE"));
            menu.setStr("SY_PRODUCT_NAME",product.getStr("PRODUCT_NAME"));
            menu.setStr("SY_STATUS", "1");
            menu.setStr("MENU_ICON", dynaBean.getStr("MENU_ICON"));
            menu.setStr("MENU_FUNCTYPE","grid");
            menu.setStr("SY_NODETYPE", NodeType.LEAF);
            commonService.buildModelCreateInfo(menu);
            menu = menuRpcService.doSave(menu);
            //将父节点类型更新为GENERAL
            DynaBean menuParent = metaRbacService.selectOneByPk("JE_CORE_MENU",dynaBean.getStr("MENU_SY_PARENT"));
            if(menuParent!=null&&NodeType.LEAF.equals(menuParent.getStr("SY_NODETYPE"))){
                metaRbacService.executeSql("UPDATE JE_CORE_MENU SET SY_NODETYPE={0} WHERE JE_CORE_MENU_ID={1}",NodeType.GENERAL,dynaBean.getStr("MENU_SY_PARENT"));
            }
        }
        /**
         * 授权给开发人员
         */
        String authorization = dynaBean.getStr("AUTHORIZATION");
        if ("1".equals(authorization)) {
            //如果不创建菜单，则授权当前功能，否则授权菜单
            if("1".equals(createMenu)){
                permissionRpcService.quickGrantMenu(dynaBean.getStr("SY_PRODUCT_ID"),menu.getStr("JE_CORE_MENU_ID"));
            }else{
                permissionRpcService.quickGranFunc(dynaBean.getStr("SY_PRODUCT_ID"),id);
            }

            //清除缓存
            String accountId = SecurityUserHolder.getCurrentAccountId();
            permissionRpcService.clearAccountPermissions(SecurityUserHolder.getCurrentAccountTenantId(),Splitter.on(",").splitToList(accountId));
        }
        return dynaBean;
    }

    @Override
    public Map<String,Object> getHomePageInfo() {
        Map<String,Object> result =new HashMap<>();
        //资源表按人员分组
        String userTableSql = "SELECT COUNT(JE_CORE_RESOURCETABLE_ID) count,SY_CREATEUSERNAME,SY_CREATEUSERID from je_core_resourcetable where  SY_NODETYPE='LEAF' AND SY_CREATEUSERID IS NOT NULL GROUP BY SY_CREATEUSERID";
        if(ConstantVars.STR_DM.equals(JEDatabase.getCurrentDatabase())){
            userTableSql = "SELECT /*+ GROUP_OPT_FLAG(1)*/ COUNT(JE_CORE_RESOURCETABLE_ID) count,SY_CREATEUSERNAME,SY_CREATEUSERID from je_core_resourcetable where  SY_NODETYPE='LEAF' AND SY_CREATEUSERID IS NOT NULL GROUP BY SY_CREATEUSERID";
        }
        List<Map<String,Object>> userTableCount = metaService.selectSql(userTableSql);
        for(Map<String,Object> map:userTableCount){
            String userName = map.get("SY_CREATEUSERNAME").toString();
            if("超级管理员".equals(userName)){
                map.put("accountCode","admin");
            }else{
                String userId = map.get("SY_CREATEUSERID").toString();
                DynaBean account = metaRbacService.selectOneByNativeQuery("JE_RBAC_ACCOUNT",NativeQuery.build().eq("USER_ASSOCIATION_ID",userId));
                map.put("accountCode",account==null?null:account.getStr("ACCOUNT_CODE"));
            }

        }
        result.put("userTableCount",userTableCount);
        //资源表按类型分组
        String typeTableSql = "SELECT COUNT(JE_CORE_RESOURCETABLE_ID) count, RESOURCETABLE_TYPE from je_core_resourcetable where RESOURCETABLE_TYPE is not null and SY_NODETYPE='LEAF'  GROUP BY RESOURCETABLE_TYPE";
        if(ConstantVars.STR_DM.equals(JEDatabase.getCurrentDatabase())){
            typeTableSql ="SELECT /*+ GROUP_OPT_FLAG(1)*/ COUNT(JE_CORE_RESOURCETABLE_ID) count, RESOURCETABLE_TYPE from je_core_resourcetable where RESOURCETABLE_TYPE is not null and SY_NODETYPE='LEAF'  GROUP BY RESOURCETABLE_TYPE";
        }
        List<Map<String,Object>> typeTableCount = metaService.selectSql(typeTableSql);
        result.put("typeTableCount",typeTableCount);
        //资源表按产品分组
        String productTableSql = "SELECT COUNT(JE_CORE_RESOURCETABLE_ID) count, SY_PRODUCT_NAME from je_core_resourcetable r where SY_NODETYPE='LEAF' AND EXISTS (SELECT JE_PRODUCT_MANAGE_ID FROM je_product_manage m WHERE r.SY_PRODUCT_ID=m.JE_PRODUCT_MANAGE_ID AND PRODUCT_ENABLE_STATE='1')  GROUP BY SY_PRODUCT_ID";
        if(ConstantVars.STR_DM.equals(JEDatabase.getCurrentDatabase())){
            productTableSql="SELECT /*+ GROUP_OPT_FLAG(1)*/ COUNT(JE_CORE_RESOURCETABLE_ID) count, SY_PRODUCT_NAME from je_core_resourcetable r where SY_NODETYPE='LEAF' AND EXISTS (SELECT JE_PRODUCT_MANAGE_ID FROM je_product_manage m WHERE r.SY_PRODUCT_ID=m.JE_PRODUCT_MANAGE_ID AND PRODUCT_ENABLE_STATE='1')  GROUP BY SY_PRODUCT_ID";
        }
        List<Map<String,Object>> productTableCount = metaService.selectSql(productTableSql);
        result.put("productTableCount",productTableCount);
        return result;
    }

    @Override
    public String checkTableForApply(String tableId) {
        DynaBean resourceTable = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", tableId);
        Boolean jeCore = ("1".equals(resourceTable.getStr("SY_JECORE")));
        String tableCode = resourceTable.getStr("RESOURCETABLE_TABLECODE");

        List<DynaBean> columns = metaService.select(ConditionsWrapper.builder().table("JE_CORE_TABLECOLUMN")
                .apply("TABLECOLUMN_RESOURCETABLE_ID={0} ORDER BY TABLECOLUMN_CLASSIFY ASC,SY_ORDERINDEX ASC", resourceTable.getStr("JE_CORE_RESOURCETABLE_ID")));

        List<DynaBean> keys = metaService.select(ConditionsWrapper.builder().table("JE_CORE_TABLEKEY")
                .eq("TABLEKEY_RESOURCETABLE_ID", resourceTable.getStr("JE_CORE_RESOURCETABLE_ID")));

        List<DynaBean> indexs = metaService.select("JE_CORE_TABLEINDEX",
                ConditionsWrapper.builder().eq("TABLEINDEX_RESOURCETABLE_ID", resourceTable.getStr("JE_CORE_RESOURCETABLE_ID")));
        String errors="";
        if(StringUtil.isEmpty(errors)){
            //如果表未创建，检查表是否已存在于数据库
            if(!"1".equals(resourceTable.getStr("RESOURCETABLE_ISCREATE"))){
              String count = checkTableExists(tableCode,resourceTable.getStr("SY_PRODUCT_CODE"));
              if(!"0".equals(count)){
                  errors = MessageUtils.getMessage("table.exits",tableCode);
              }
            }
        }
        if(StringUtil.isEmpty(errors)){
            //对列进行校验
            errors = metaTableColumnService.checkColumns(columns, jeCore);
        }
        if (StringUtil.isEmpty(errors)) {
            //对键进行校验
            errors = metaTableKeyService.checkKeys(keys);
        }

        if (StringUtil.isEmpty(errors)) {
            //对索引进行校验
            errors = metaTableIndexService.checkIndexs(indexs);
        }
        return errors;
    }

    @Override
    public String getSqlViewSelect(String sqlType,String column, String whereSql, String sort, String limit,String RESOURCETABLE_TABLECODE) {
        String sql = "";
        if("selectSql".equals(sqlType)){
            sql = getSelectSql(column,whereSql,sort,limit,RESOURCETABLE_TABLECODE,sqlType);
            sql = queryBuilderService.formatSqlParameter(sql);
        }
        if("insterSql".equals(sqlType) || "insterNoSYSql".equals(sqlType)){
            sql = getInsertSql(column,RESOURCETABLE_TABLECODE,sqlType);
        }
        if("updateSql".equals(sqlType)){
            sql =getUpdateSql(column,whereSql,RESOURCETABLE_TABLECODE,sqlType);
            sql = queryBuilderService.formatSqlParameter(sql);
        }
        if("deleteSql".equals(sqlType)){
            sql = getDeleteSql(whereSql,RESOURCETABLE_TABLECODE);
            sql = queryBuilderService.formatSqlParameter(sql);
        }
        return sql;
    }

    private String getInsertSql(String column, String tableCode,String sqlType) {
        String columnSql = formatColumn(column,tableCode,sqlType);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(" INSERT INTO ");
        stringBuilder.append(" "+tableCode+" ");
        stringBuilder.append(columnSql);
        return stringBuilder.toString();
    }

    private String getDeleteSql(String whereSql, String tableCode) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(" DELETE ");
        stringBuilder.append(" FROM ");
        stringBuilder.append(" "+tableCode+" ");
        if(StringUtil.isNotEmpty(whereSql)){
            stringBuilder.append(" WHERE ");
            stringBuilder.append(whereSql);
        }
        return stringBuilder.toString();
    }

    private String getUpdateSql(String column, String whereSql, String tableCode,String sqlType) {
        String columnSql = formatColumn(column,tableCode,sqlType);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(" UPDATE ");
        stringBuilder.append(" "+tableCode+" ");
        stringBuilder.append("\n");
        stringBuilder.append(" SET ");
        stringBuilder.append("\n");
        stringBuilder.append("  ");
        stringBuilder.append(columnSql);
        if(StringUtil.isNotEmpty(whereSql)){
            stringBuilder.append(" WHERE ");
            stringBuilder.append(whereSql);
        }
        return stringBuilder.toString();
    }


    private String getSelectSql(String column, String whereSql, String sort, String limit, String tableCode,String sqlType) {
        String columnSql = formatColumn(column,tableCode,sqlType);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(" SELECT ");
        stringBuilder.append("\n");
        stringBuilder.append(columnSql);
        stringBuilder.append(" FROM ");
        stringBuilder.append("\n");
        stringBuilder.append("  ");
        stringBuilder.append(tableCode);
        if(StringUtil.isNotEmpty(whereSql)){
            stringBuilder.append("\n");
            stringBuilder.append(" WHERE ");
            stringBuilder.append(whereSql).append(" ");
            if(StringUtil.isNotEmpty(limit)){
                if(ConstantVars.STR_ORACLE.equals(JEDatabase.getCurrentDatabase())){
                    stringBuilder.append(" rownum <= ").append(limit);
                }
            }
        }

        if(StringUtil.isNotEmpty(sort)){
            stringBuilder.append("\n");
            stringBuilder.append(" ORDER BY ");
            stringBuilder.append(sort);
        }
        if(StringUtil.isNotEmpty(limit)){
            if(!ConstantVars.STR_ORACLE.equals(JEDatabase.getCurrentDatabase())) {
                stringBuilder.append("\n");
                stringBuilder.append(" LIMIT ");
                stringBuilder.append(limit);
            }
        }

        return stringBuilder.toString();
    }

    private String formatColumn(String column, String tableCode,String sqlType) {
        ConditionsWrapper conditionsWrapper = ConditionsWrapper.builder()
                .eq("TABLECOLUMN_TABLECODE",tableCode).eq("TABLECOLUMN_ISCREATE","1");
        if(StringUtil.isNotEmpty(column)){
            conditionsWrapper.in("TABLECOLUMN_CODE",Arrays.asList(column.split(",")));
        }

        if("insterNoSYSql".equals(sqlType)){
            conditionsWrapper.apply(" AND (TABLECOLUMN_CLASSIFY!='SYS' or TABLECOLUMN_TYPE='ID')");
        }
        List<DynaBean> list = metaService.select("JE_CORE_TABLECOLUMN",conditionsWrapper.orderByAsc("TABLECOLUMN_CLASSIFY"));
        StringBuilder stringBuilder = new StringBuilder();
        if("updateSql".equals(sqlType)){
            for(int i=0;i<list.size();i++){
                DynaBean dynaBean = list.get(i);
                stringBuilder.append(dynaBean.getStr("TABLECOLUMN_CODE"));
                stringBuilder.append("=");
                stringBuilder.append("NULL");
                if(i!=list.size()-1){
                    stringBuilder.append(",");
                }
                stringBuilder.append(" -- ");
                stringBuilder.append(dynaBean.getStr("TABLECOLUMN_NAME"));
                stringBuilder.append(" ");
                stringBuilder.append(getColumnDesc(dynaBean.getStr("TABLECOLUMN_TYPE"),dynaBean.getStr("TABLECOLUMN_LENGTH")));
                stringBuilder.append("\n");
                stringBuilder.append("  ");
            }
        } else if ("insterSql".equals(sqlType) || "insterNoSYSql".equals(sqlType)) {
            stringBuilder.append("\n");
            stringBuilder.append(" (");
            stringBuilder.append("\n");
            stringBuilder.append("  ");
            for(int i=0;i<list.size();i++){
                DynaBean dynaBean = list.get(i);
                stringBuilder.append(dynaBean.getStr("TABLECOLUMN_CODE"));
                if(i!=list.size()-1){
                    stringBuilder.append(",");
                }
                stringBuilder.append(" -- ");
                stringBuilder.append(dynaBean.getStr("TABLECOLUMN_NAME"));
                stringBuilder.append(" ");
                stringBuilder.append(getColumnDesc(dynaBean.getStr("TABLECOLUMN_TYPE"),dynaBean.getStr("TABLECOLUMN_LENGTH")));
                stringBuilder.append("\n");
                if(i!=list.size()-1){
                    stringBuilder.append("  ");
                }
            }
            stringBuilder.append(" )");
            stringBuilder.append("\n");
            stringBuilder.append(" VALUES ");
            stringBuilder.append("\n");
            stringBuilder.append(" (");
            stringBuilder.append("\n");
            stringBuilder.append("  ");
            for(int i=0;i<list.size();i++){
                DynaBean dynaBean = list.get(i);
                stringBuilder.append("NULL");
                if(i!=list.size()-1){
                    stringBuilder.append(",");
                }
                stringBuilder.append(" -- ");
                stringBuilder.append(dynaBean.getStr("TABLECOLUMN_NAME"));
                stringBuilder.append(" ");
                stringBuilder.append(getColumnDesc(dynaBean.getStr("TABLECOLUMN_TYPE"),dynaBean.getStr("TABLECOLUMN_LENGTH")));
                stringBuilder.append("\n");
                if(i!=list.size()-1){
                    stringBuilder.append("  ");
                }
            }
            stringBuilder.append(" )");
        } else if("selectSql".equals(sqlType)){
            for(int i=0;i<list.size();i++){
                DynaBean dynaBean = list.get(i);
                stringBuilder.append("  ");
                stringBuilder.append(dynaBean.getStr("TABLECOLUMN_CODE"));
                if(i!=list.size()-1){
                    stringBuilder.append(",");
                }
                stringBuilder.append(" -- ");
                stringBuilder.append(dynaBean.getStr("TABLECOLUMN_NAME"));
                stringBuilder.append(" ");
                stringBuilder.append(getColumnDesc(dynaBean.getStr("TABLECOLUMN_TYPE"),dynaBean.getStr("TABLECOLUMN_LENGTH")));
                stringBuilder.append("\n");
            }
        }
        return stringBuilder.toString();

    }

    private String getColumnDesc(String columnType,String length) {
        if(ColumnType.VARCHAR.equals(columnType)){
            return "("+ColumnEnum.valueOf(columnType).getDesc()+length+")";
        }
        if(ColumnType.CUSTOM.equals(columnType) || ColumnType.CUSTOMFOREIGNKEY.equals(columnType) || ColumnType.CUSTOMID.equals(columnType) ){
            return "("+ColumnEnum.valueOf(columnType).getDesc()+(length)+")";
        }
        return "("+ColumnEnum.valueOf(columnType).getDesc()+")";
    }

    @Override
    public String deleteCheck(String tableId) {
        //校验是否属于视图的基表
        List<DynaBean> list = metaService.select("JE_CORE_RESOURCETABLE",
                ConditionsWrapper.builder().eq("RESOURCETABLE_TYPE", "VIEW").like("RESOURCETABLE_TABLESINFO", tableId));
        if (list != null && list.size() > 0) {
            return MessageUtils.getMessage("table.coannot.delete");
        }
        //校验是否存在子表
        DynaBean resourceTable = metaService.selectOneByPk("JE_CORE_RESOURCETABLE",tableId);
        String childCodes = resourceTable.getStr("RESOURCETABLE_CHILDTABLECODES", "");
        if (StringUtil.isNotEmpty(childCodes)) {
            return MessageUtils.getMessage("table.detele.constraint");
        }
        return null;
    }

    private String checkTableExists(String tableCode, String productCode) {
        if(PRODUCT_CORE_META.equals(productCode)){
            return DataBaseUtils.checkTableExists(tableCode);
        }else{
            CommonTableRpcService commonTableRpcService = RpcSchemaFactory.getRemoteProvierClazz(productCode,
                    "commonTableRpcService", CommonTableRpcService.class);

            return commonTableRpcService.checkTableExists(tableCode);
        }
    }

    private StringBuilder generationSelectSqlByTatal(String tableCode, JSONArray whereList, JSONArray orderList) {
        StringBuilder sql = new StringBuilder("SELECT *");
        sql.append(" FROM " + tableCode);
        sql.append(getWhereDdl(whereList));
        sql.append(getOrderDdl(orderList));
        return sql;
    }

    private StringBuilder generationSelectSql(JSONArray columnList, String tableCode, JSONArray whereList, JSONArray orderList) {
        StringBuilder sql = new StringBuilder("SELECT ");
        sql.append(getColumnDdl(columnList, tableCode));
        sql.append(" FROM " + tableCode);
        sql.append(getWhereDdl(whereList));
        sql.append(getOrderDdl(orderList));
        return sql;
    }


    private static String insert = "INSERT INTO";//插入sql
    private static String values = "VALUES";//values关键字

    /**
     * 生成插入sql
     *
     * @param columnList
     * @param list
     * @param tableCode
     * @return
     */
    @Override
    public List<String> generateInsertSQL(JSONArray columnList, List<Map<String, Object>> list, String tableCode, boolean status) {
        List<DynaBean> keys = metaService.select("JE_CORE_TABLEKEY",
                ConditionsWrapper.builder().eq("TABLEKEY_TABLECODE", tableCode));
        String primaryCode = tableCode + "_ID";
        for (DynaBean key : keys) {
            if ("Primary".equals(key.getStr("TABLEKEY_TYPE"))) {
                primaryCode = key.getStr("TABLEKEY_COLUMNCODE");
            }
        }
        if (!columnList.contains(primaryCode)) {
            columnList.add(primaryCode);
        }
        List<String> resultList = new ArrayList<>(30);
        StringBuffer columnName = new StringBuffer();
        for (int i = 0, size = columnList.size(); i < size; i++) {
            columnName.append(columnList.getString(i));
            if (size - 1 != i) {
                columnName.append(",");
            }
        }

        for (int i = 0, size = list.size(); i < size; i++) {
            StringBuffer columnValue = new StringBuffer();
            Map<String, Object> columnValueMap = list.get(i);
            for (int j = 0, colSize = columnList.size(); j < colSize; j++) {
                columnValue.append("'");
                columnValue.append(columnValueMap.get(columnList.getString(j)));
                columnValue.append("'");
                if (columnList.size() - 1 != j) {
                    columnValue.append(",");
                }
            }
            if (columnList.size() == 0) {
                resultList.add(insertAllSQL(list.get(i), tableCode));
            } else {
                if (status) {
                    resultList.add(insertAllSQL(list.get(i), tableCode));
                } else {
                    resultList.add(insertSQL(columnName, columnValue, tableCode));
                }
            }
        }
        return resultList;
    }

    private String insertAllSQL(Map<String, Object> map, String tableCode) {
        StringBuffer columnName = new StringBuffer();
        StringBuffer columnValue = new StringBuffer();
        int i = 0;
        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            if ("$TABLE_CODE$".equals(entry.getKey())) {
                continue;
            }
            columnName.append(entry.getKey());

            columnValue.append("'");
            columnValue.append(entry.getValue());
            columnValue.append("'");
            if (map.size() - 2 != i) {
                columnName.append(",");
                columnValue.append(",");
            }
            i++;
        }

        StringBuffer insertSQL = new StringBuffer();
        insertSQL.append(insert)
                .append(" ")
                .append(tableCode)
                .append("(")
                .append(columnName.toString())
                .append(")")
                .append(values)
                .append("(")
                .append(columnValue.toString())
                .append(");");
        return insertSQL.toString();

    }

    /**
     * 获取父表信息
     *
     * @param table
     * @return
     */
    @Override
    public List<TableDataView> selectParentTable(DynaBean table) {
        List<TableDataView> parentList = new ArrayList<>(10);
        String tableCode = table.getStr("RESOURCETABLE_TABLECODE");
        String parentCodes = table.getStr("RESOURCETABLE_PARENTTABLECODES", "");
        if (StringUtil.isNotEmpty(parentCodes)) {
            List<DynaBean> parentTables = metaService.select("JE_CORE_RESOURCETABLE",
                    ConditionsWrapper.builder().in("RESOURCETABLE_TABLECODE", parentCodes.split(",")));
            for (DynaBean parentTable : parentTables) {
                if (tableCode.equals(parentTable.getStr("RESOURCETABLE_TABLECODE"))) {
                    continue;
                }
                TableDataView tableVo = new TableDataView();
                tableVo.setId(parentTable.getStr("JE_CORE_RESOURCETABLE_ID"));
                tableVo.setTableCode(parentTable.getStr("RESOURCETABLE_TABLECODE"));
                tableVo.setTableName(parentTable.getStr("RESOURCETABLE_TABLENAME"));
                tableVo.setTableType("PARENT");
                parentList.add(tableVo);
            }
        }
        return parentList;
    }

    /**
     * 获取子表信息
     *
     * @param table
     * @return
     */
    @Override
    public List<TableDataView> selectChildTable(DynaBean table) {
        List<TableDataView> childtList = new ArrayList<>(10);
        String tableCode = table.getStr("RESOURCETABLE_TABLECODE");
        String childCodes = table.getStr("RESOURCETABLE_CHILDTABLECODES", "");
        if (StringUtil.isNotEmpty(childCodes)) {
            List<DynaBean> childTables = metaService.select("JE_CORE_RESOURCETABLE",
                    ConditionsWrapper.builder().in("RESOURCETABLE_TABLECODE", childCodes.split(",")));
            TableDataView tableVo;
            for (DynaBean childTable : childTables) {
                if (tableCode.equals(childTable.getStr("RESOURCETABLE_TABLECODE"))) {
                    continue;
                }
                tableVo = new TableDataView();
                tableVo.setId(childTable.getStr("JE_CORE_RESOURCETABLE_ID"));
                tableVo.setTableCode(childTable.getStr("RESOURCETABLE_TABLECODE"));
                tableVo.setTableName(childTable.getStr("RESOURCETABLE_TABLENAME"));
                tableVo.setTableType("CHILD");
                childtList.add(tableVo);
            }
        }
        return childtList;
    }

    /**
     * 获取该表下所有视图信息
     *
     * @param table
     * @return
     */
    @Override
    public List<TableDataView> selectTableByView(DynaBean table) {
        List<TableDataView> tableByViewList = new ArrayList<>(10);
        String resourceId = table.getPkCode();
        List<Map<String, Object>> list = metaService.selectSql("SELECT TABLEVIEW_RESOURCETABLE_ID,TABLEVIEW_VIEWCODE,TABLEVIEW_VIEWNAME FROM JE_CORE_TABLEVIEW WHERE TABLEVIEW_RESOURCETABLE_ID={0}", resourceId);
        TableDataView tableVo;
        for (int i = 0, size = list.size(); i < size; i++) {
            Map<String, Object> viewMap = list.get(i);
            tableVo = new TableDataView();
            tableVo.setId(String.valueOf(viewMap.get("TABLEVIEW_RESOURCETABLE_ID")));
            tableVo.setTableCode(String.valueOf(viewMap.get("TABLEVIEW_VIEWCODE")));
            tableVo.setTableName(String.valueOf(viewMap.get("TABLEVIEW_VIEWNAME")));
            tableByViewList.add(tableVo);
        }
        return tableByViewList;
    }

    /**
     * 获取该表下所有主子功能
     *
     * @param table
     * @return
     */
    public List<List<TableDataView>> selectTableByFuncTEST(DynaBean table) {
        //查询
        List<List<TableDataView>> resultList = new ArrayList<>();
        List<DynaBean> funcInfos = metaService.select("JE_CORE_FUNCINFO",
                ConditionsWrapper.builder()
                        .eq("FUNCINFO_TABLENAME", table.getStr("RESOURCETABLE_TABLECODE"))
                        .eq("FUNCINFO_NODEINFOTYPE", "FUNC"));
        TableDataView tableVo;
        for (DynaBean func : funcInfos) {
            List<TableDataView> tableByFuncList = new ArrayList<>(10);

            String rootParentpathId = null;
            String syParentpath = func.getStr("SY_PARENTPATH") + "/" + func.getPkValue();
            String[] syParentpathIds = syParentpath.split("/");
            for (int i = syParentpathIds.length - 1; i >= 1; --i) {
                String syParentpathId = syParentpathIds[i];
                DynaBean funcBaen = metaService.selectOne("JE_CORE_FUNCINFO", ConditionsWrapper.builder().eq("JE_CORE_FUNCINFO_ID", syParentpathId)
                        .eq("FUNCINFO_NODEINFOTYPE", "FUNC"));
                if (null == funcBaen) {
                    rootParentpathId = syParentpathIds[i + 1];
                    break;
                }
            }

            List<Map<String, Object>> childrenFuncList = metaService.selectSql("SELECT * FROM JE_CORE_FUNCINFO WHERE SY_PARENTPATH LIKE '%" + "/" + rootParentpathId + "%'");
            for (int i = 0; i < childrenFuncList.size(); i++) {
                Map<String, Object> childFunc = childrenFuncList.get(i);
                tableVo = new TableDataView();
                tableVo.setId(childFunc.get("JE_CORE_FUNCINFO_ID").toString());
                tableVo.setTableCode(childFunc.get("FUNCINFO_FUNCCODE").toString());
                tableVo.setTableName(childFunc.get("FUNCINFO_FUNCNAME").toString());
                tableByFuncList.add(tableVo);
            }
            if (null == childrenFuncList || childrenFuncList.size() == 0) {
                DynaBean funcBaen = metaService.selectOne("JE_CORE_FUNCINFO", ConditionsWrapper.builder().eq("JE_CORE_FUNCINFO_ID", func.getPkValue())
                        .eq("FUNCINFO_NODEINFOTYPE", "FUNC"));
                tableVo = new TableDataView();
                tableVo.setId(funcBaen.get("JE_CORE_FUNCINFO_ID").toString());
                tableVo.setTableCode(funcBaen.get("FUNCINFO_FUNCCODE").toString());
                tableVo.setTableName(funcBaen.get("FUNCINFO_FUNCNAME").toString());
                tableByFuncList.add(tableVo);
            }
            tableByFuncList = selectFuncRelation(tableByFuncList);
            resultList.add(tableByFuncList);
        }
        return resultList;
    }

    /**
     * 获取该表下所有主子功能
     *
     * @param table
     * @return
     */
    public List<TableDataView> selectTableByFuncA(DynaBean table) {
        List<TableDataView> tableDataViews = new ArrayList<>();
        List<DynaBean> funcInfos = metaService.select("JE_CORE_FUNCINFO",
                ConditionsWrapper.builder()
                        .eq("FUNCINFO_TABLENAME", table.getStr("RESOURCETABLE_TABLECODE"))
                        .eq("FUNCINFO_NODEINFOTYPE", "FUNC"));
        tableDataViews = buildTableDateView(funcInfos, tableDataViews);
        return tableDataViews;
    }

    private List<TableDataView> buildTableDateView(List<DynaBean> funcInfos, List<TableDataView> tableDataViews) {
        TableDataView tableVo;
        for (DynaBean func : funcInfos) {

            tableVo = new TableDataView();
            tableVo.setId(func.get("JE_CORE_FUNCINFO_ID").toString());
            tableVo.setTableCode(func.get("FUNCINFO_FUNCCODE").toString());
            tableVo.setTableName(func.get("FUNCINFO_FUNCNAME").toString());
            tableDataViews.add(tableVo);

            String rootParentpathId = null;
            String syParentpath = func.getStr("SY_PARENTPATH");
            String[] syParentpathIds = syParentpath.split("/");
            for (int i = 0; i < syParentpathIds.length; i++) {
                String syParentpathId = syParentpathIds[i];
                DynaBean funcBaen = metaService.selectOne("JE_CORE_FUNCINFO", ConditionsWrapper.builder().eq("JE_CORE_FUNCINFO_ID", syParentpathId)
                        .eq("FUNCINFO_NODEINFOTYPE", "FUNC"));
                if (null == funcBaen) {
                    rootParentpathId = syParentpathIds[i];
                    break;
                }
            }
            List<DynaBean> childrenFuncList = metaService.select("JE_CORE_FUNCINFO",
                    ConditionsWrapper.builder()
                            .like("SY_PARENTPATH", rootParentpathId));
            //tableDataViews = selectFuncRelation(tableDataViews);
            if (null != childrenFuncList) {
                tableDataViews = buildTableDateView(childrenFuncList, tableDataViews);
            } else {
                tableVo.setDataList(tableDataViews);
            }
        }
        return tableDataViews;
    }


    /**
     * 获取该表下所有主子功能
     *
     * @param table
     * @return
     */
    @Override
    public List<TableDataView> selectTableByFunc(DynaBean table) {
        List<TableDataView> tableByFuncList = new ArrayList<>(10);
        List<DynaBean> funcInfos = metaService.select("JE_CORE_FUNCINFO",
                ConditionsWrapper.builder()
                        .eq("FUNCINFO_TABLENAME", table.getStr("RESOURCETABLE_TABLECODE"))
                        .eq("FUNCINFO_NODEINFOTYPE", "FUNC"));
        TableDataView tableVo;
        for (DynaBean func : funcInfos) {
            tableVo = new TableDataView();
            tableVo.setId(func.getStr("JE_CORE_FUNCINFO_ID"));
            tableVo.setTableCode(func.getStr("FUNCINFO_FUNCCODE"));
            tableVo.setTableName(func.getStr("FUNCINFO_FUNCNAME"));
            tableByFuncList.add(tableVo);
        }
        tableByFuncList = selectFuncRelation(tableByFuncList);
        return tableByFuncList;
    }

    /**
     * 获取该表下所有菜单信息
     *
     * @return
     */
    @Override
    public List<TableDataView> selectTableByMenus(List<String> funcCodes) {
        List<DynaBean> menuList = metaRbacService.selectByTableCodeAndNativeQuery("JE_CORE_MENU", NativeQuery.build().in("MENU_NODEINFO", funcCodes));
        List<TableDataView> tableByMenusList = new ArrayList<>(10);
        TableDataView tableDataView;
        if (menuList != null && menuList.size() > 0) {
            for (int i = 0, size = menuList.size(); i < size; i++) {
                String syPath = String.valueOf(menuList.get(i).get("SY_PATH"));
                String[] split = syPath.split("/");
                List<DynaBean> menuResult = metaRbacService.selectByTableCodeAndNativeQuery("JE_CORE_MENU", NativeQuery.build().eq("JE_CORE_MENU_ID", split[split.length - 1]));
                DynaBean dynaBean = menuResult.get(0);
                StringBuffer tableName = new StringBuffer();
                tableDataView = new TableDataView();
                tableDataView.setId(dynaBean.getStr("JE_CORE_MENU_ID"));
                tableDataView.setTableCode(dynaBean.getStr("MENU_NODEINFO"));
                tableDataView.setTableType(String.valueOf(i));

                for (int j = 1, solitSize = split.length-1; j < solitSize; j++) {
                    List<DynaBean> menuResultParent = metaRbacService.selectByTableCodeAndNativeQuery("JE_CORE_MENU", NativeQuery.build().eq("JE_CORE_MENU_ID", split[j]));
                    DynaBean parentDynBean = menuResultParent.get(0);
                    tableName.append(parentDynBean.getStr("MENU_MENUNAME") + "-》 ");
                }
                tableDataView.setTableName(tableName.append(dynaBean.get("MENU_MENUNAME")).toString());
                tableByMenusList.add(tableDataView);

            }
        }
        return tableByMenusList;
    }

    /**
     * 转移模块表等操作
     *
     * @param resourceId
     * @param toResourceId
     * @return
     */
    @Override
    public DynaBean move(String resourceId, String toResourceId, String place) {
        String tableCode = "JE_CORE_RESOURCETABLE";
        String pkName = "JE_CORE_RESOURCETABLE_ID";
        DynaBean fromBean = metaService.selectOneByPk(tableCode, resourceId);
        String oldTreeIndex = fromBean.getStr("SY_TREEORDERINDEX");
        DynaBean toResource = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", toResourceId);
        String orderIndex = "";
        String treeOrderIndex = "";
        if (null == toResource) {
            throw new PlatformException(MessageUtils.getMessage("table.move.notNode"), PlatformExceptionEnum.JE_CORE_TABLE_UPDATE_ERROR);
        }
        //在上面 在下面
        if (place.equals(ABOVE) || place.equals(BELOW)) {
            treeOrderIndex = toResource.getStr("SY_TREEORDERINDEX");
            orderIndex = toResource.getStr("SY_ORDERINDEX");
            toResource = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", toResource.getStr("SY_PARENT"));
            toResourceId = toResource.getPkValue();
            if (null == toResource) {
                throw new PlatformException(MessageUtils.getMessage("table.move.notNode"), PlatformExceptionEnum.JE_CORE_TABLE_UPDATE_ERROR);
            }
        }
        String oldPath = fromBean.getStr("SY_PATH");
        String oldParentPath = fromBean.getStr("SY_PARENTPATH");
        String fromOldParentId = fromBean.getStr("SY_PARENT");
        //验证，不能转移到表中，不能转移到子数据下
        String type = toResource.getStr("RESOURCETABLE_TYPE");
        if (!type.equals("MODULE")) {
            throw new PlatformException(MessageUtils.getMessage("table.move.onlyModule"), PlatformExceptionEnum.JE_CORE_TABLE_UPDATE_ERROR);
        }
        String path = toResource.getStr("SY_PATH");
        if (path.indexOf(resourceId) >= 0) {
            throw new PlatformException(MessageUtils.getMessage("table.move.onlyChildModule"), PlatformExceptionEnum.JE_CORE_TABLE_UPDATE_ERROR);
        }
        //更新当前模块排序
        if (place.equals(ABOVE) && !Strings.isNullOrEmpty(treeOrderIndex) && !Strings.isNullOrEmpty(orderIndex)) {
            fromBean.setStr("SY_TREEORDERINDEX", treeOrderIndex);
            fromBean.setStr("SY_ORDERINDEX", orderIndex);
            String sql = String.format("UPDATE JE_CORE_RESOURCETABLE SET SY_ORDERINDEX = SY_ORDERINDEX+1,SY_TREEORDERINDEX = SY_TREEORDERINDEX+1 " +
                            "WHERE SY_PARENT ='%s' AND SY_ORDERINDEX >= %s ",
                    toResource.getPkValue(), orderIndex);
            List<DynaBean> list = metaService.select("JE_CORE_RESOURCETABLE", ConditionsWrapper.builder().
                    eq("SY_PARENT", toResource.getPkValue()).ge("SY_ORDERINDEX", orderIndex));
            for (DynaBean dynaBean : list) {
                dynaBean.set("SY_ORDERINDEX", dynaBean.getInt("SY_ORDERINDEX") + 1);
                String treeIndex = dynaBean.getStr("SY_TREEORDERINDEX");
                int length = treeIndex.length();
                if (treeIndex.length() < 6) {
                    continue;
                }
                int i = Integer.parseInt(treeIndex.substring(treeIndex.length() - 6));
                DecimalFormat df = new DecimalFormat("000000");
                String lengthStr = df.format(i + 1);
                dynaBean.setStr("SY_TREEORDERINDEX", treeIndex.substring(0, treeIndex.length() - 6) + lengthStr);
                metaService.update(dynaBean);
            }
        } else if (place.equals(BELOW) && !Strings.isNullOrEmpty(treeOrderIndex) && !Strings.isNullOrEmpty(orderIndex)) {
            if (treeOrderIndex.length() >= 6) {
                int i = Integer.parseInt(treeOrderIndex.substring(treeOrderIndex.length() - 6));
                DecimalFormat df = new DecimalFormat("000000");
                String lengthStr = df.format(i + 1);
                fromBean.setStr("SY_TREEORDERINDEX", treeOrderIndex.substring(0, treeOrderIndex.length() - 6) + lengthStr);
            }
            fromBean.setStr("SY_ORDERINDEX", Integer.toString(Integer.parseInt(orderIndex) + 1));
            List<DynaBean> list = metaService.select("JE_CORE_RESOURCETABLE", ConditionsWrapper.builder().eq("SY_PARENT", toResource.getPkValue()).gt("SY_ORDERINDEX", orderIndex));
            for (DynaBean dynaBean : list) {
                dynaBean.set("SY_ORDERINDEX", dynaBean.getInt("SY_ORDERINDEX") + 1);
                String treeIndex = dynaBean.getStr("SY_TREEORDERINDEX");
                int length = treeIndex.length();
                if (treeIndex.length() < 6) {
                    continue;
                }
                int i = Integer.parseInt(treeIndex.substring(treeIndex.length() - 6));
                DecimalFormat df = new DecimalFormat("000000");
                String lengthStr = df.format(i + 1);
                dynaBean.setStr("SY_TREEORDERINDEX", treeIndex.substring(0, treeIndex.length() - 6) + lengthStr);
                metaService.update(dynaBean);
            }
        } else {
            fromBean.setStr("SY_TREEORDERINDEX", toResource.getStr("SY_TREEORDERINDEX"));
            fromBean.set("SY_PARENT", toResourceId);
            fromBean.setStr("SY_ORDERINDEX", "");
            commonService.generateTreeOrderIndex(fromBean);
        }
        //设置父级id ,当前path ,父级path
        String SY_PATH = toResource.getStr("SY_PATH") + "/" + resourceId;
        String SY_PARENTPATH = toResource.getStr("SY_PATH");
        fromBean.set("SY_PARENTPATH", SY_PARENTPATH);
        fromBean.set("SY_PATH", SY_PATH);
        fromBean.set("SY_PARENT", toResourceId);
        metaService.update(fromBean);
        //更新当前节点下所有孩子的路径信息
        getUpdateChild(oldPath, fromBean, oldTreeIndex);
        commonService.updateTreePanent4NodeType(tableCode, toResourceId);
        commonService.updateTreePanent4NodeType(tableCode, fromOldParentId);
        return fromBean;
    }

    /**
     * 获取当前节点下所有孩子的路径信息 sql
     *
     * @param fromPath          转移前的路径
     * @param afterTransferMenu 转移后的菜单bean
     * @return
     */
    private void getUpdateChild(String fromPath, DynaBean afterTransferMenu, String oldTreeorderindex) {
        List<DynaBean> list = metaService.select("JE_CORE_RESOURCETABLE", ConditionsWrapper.builder().like("SY_PARENTPATH", fromPath));
        for (DynaBean menu : list) {
            String SY_PARENTPATH = menu.getStr("SY_PARENTPATH").replace(fromPath, afterTransferMenu.getStr("SY_PATH"));
            String SY_PAT = menu.getStr("SY_PATH").replace(fromPath, afterTransferMenu.getStr("SY_PATH"));
            menu.setStr("SY_PARENTPATH", SY_PARENTPATH);
            menu.setStr("SY_PATH", SY_PAT);
            menu.setStr("SY_TREEORDERINDEX", menu.getStr("SY_TREEORDERINDEX").replace(oldTreeorderindex, afterTransferMenu.getStr("SY_TREEORDERINDEX")));
            metaService.update(menu);
        }
    }

    /**
     * 加载历史留痕
     *
     * @param resourceId
     * @return
     */
    @Override
    public List<Map<String, Object>> loadHistoricalTraces(String resourceId) {
        List<Map<String, Object>> resultList = metaService.selectSql("SELECT * FROM JE_CORE_TABLETRACE WHERE TABLETRACE_RESOURCETABLE_ID={0} ORDER BY SY_CREATETIME DESC", resourceId);
        resultList.forEach(eachData -> {
            String tableXgnrStr = String.valueOf(eachData.get("TABLETRACE_XGNRJSON"));
            JSONArray tableXgnrJon = JSONArray.parseArray(tableXgnrStr);
            eachData.put("TABLETRACE_XGNRJSON", tableXgnrJon);
        });
        return resultList;
    }

    /**
     * 根据表id获取表类型
     *
     * @param parentId
     * @return
     */
    @Override
    public String getTableType(String parentId) {
        DynaBean parent = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", parentId);
        if (parent == null) {
            return null;
        }
        return parent.getStr("RESOURCETABLE_TYPE");
    }

    /**
     * 查询表的关系视图
     *
     * @param pkValue
     * @return
     */
    @Override
    public DynaBean selectRelation(String pkValue) {
        //资源表
        DynaBean dynaBean = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", pkValue);
        //获取父表信息
        List<TableDataView> parentList = selectParentTable(dynaBean);
        //获取子表信息
        List<TableDataView> childList = selectChildTable(dynaBean);
        //获取视图信息
        List<TableDataView> viewList = selectTableByView(dynaBean);
        //获取功能信息
        List<Map<String, Object>> funcList = tableService.getRelation(dynaBean);
        List<String> funcCodes = new ArrayList<>();
        if(funcList!=null&&funcList.size()>0){
            for(Map<String,Object> map:funcList){
                funcCodes.add(map.get("FUNCINFO_FUNCCODE").toString());
            }
        }
        //获取菜单信息
        List<TableDataView> menusList = selectTableByMenus(funcCodes);
        dynaBean.set("parentList", parentList);
        dynaBean.set("childList", childList);
        dynaBean.set("viewList", viewList);
        dynaBean.set("funcList", funcList);
        dynaBean.set("menusList", menusList);
        return dynaBean;
    }

    /**
     * 同步资源表字段
     *
     * @param pkValue
     * @param ckPkValue
     */
    @Override
    public void syncTableField(String pkValue, String ckPkValue) {
        List<DynaBean> ckColumns = metaService.select("JE_CORE_TABLECOLUMN",
                ConditionsWrapper.builder().in("TABLECOLUMN_RESOURCETABLE_ID", ckPkValue.split(",")));
        List<DynaBean> columns = metaService.select("JE_CORE_TABLECOLUMN",
                ConditionsWrapper.builder().eq("TABLECOLUMN_RESOURCETABLE_ID", pkValue));
        for (DynaBean column : columns) {
            String name = column.getStr("TABLECOLUMN_NAME");
            String code = column.getStr("TABLECOLUMN_CODE");
            if (StringUtil.isNotEmpty(name)) {
                continue;
            }
            for (DynaBean ckColumn : ckColumns) {
                String ckCode = ckColumn.getStr("TABLECOLUMN_CODE");
                if (code.equals(ckCode)) {
                    column.set("TABLECOLUMN_NAME", ckColumn.getStr("TABLECOLUMN_NAME"));
                    metaService.update(column);
                    break;
                }
            }
        }
    }

    /**
     * 更换主键名
     *
     * @param pkValue
     * @param newCode
     * @return
     */
    @Override
    @Transactional
    public String changeTablePrimaryKey(String pkValue, String newCode) throws APIWarnException {
        DynaBean dynaBean = metaService.selectOneByPk("JE_CORE_RESOURCETABLE",pkValue);
        //ddl集合
        List<String> arraySql = new ArrayList<>();
        if(!"VIEW".equals(dynaBean.getStr("RESOURCETABLE_TYPE"))){
            arraySql = generateChangeTablePrimaryKeyDDL(dynaBean.getStr("RESOURCETABLE_TABLECODE"), dynaBean.getStr("RESOURCETABLE_PKCODE"), newCode);
        }
        //校验并更新元数据
        String result = changePrimaryKeyService.checkLocal(dynaBean);
        if(StringUtil.isEmpty(result)){
            changePrimaryKeyService.checkMeta(newCode,dynaBean);
        }
        if(StringUtil.isNotEmpty(result)){
            return result;
        }

        //执行ddl
        for (String sql : arraySql) {
            try {
                if (StringUtil.isNotEmpty(sql)) {
                    metaService.executeSql(sql);
                }
            } catch (Exception e) {
                String message = e.getMessage();
                if (e.getCause() != null) {
                    message = e.getCause().getMessage();
                }
                throw new PlatformException(MessageUtils.getMessage("table.update.errorInfo", arraySql, message), PlatformExceptionEnum.JE_CORE_TABLE_UPDATE_ERROR, new Object[]{arraySql}, e);
            }
        }
        changePrimaryKeyService.updateMeta(dynaBean,newCode);
        return null;
    }

    /**
     * 检查主键是否参与视图
     *
     * @param dynaBean
     * @return
     * @throws APIWarnException
     */
    private boolean isViewByBean(DynaBean dynaBean) throws APIWarnException {
        List<DynaBean> viewList = metaService.select("JE_CORE_VIEWCASCADE",
                ConditionsWrapper.builder()
                        .eq("VIEWCASCADE_YBBM", dynaBean.getStr("RESOURCETABLE_TABLECODE"))
                        .eq("VIEWCASCADE_YBZD", dynaBean.getStr("RESOURCETABLE_PKCODE"))
                        .or()
                        .eq("VIEWCASCADE_MBBBM", dynaBean.getStr("RESOURCETABLE_TABLECODE"))
                        .eq("VIEWCASCADE_MBBZD", dynaBean.getStr("RESOURCETABLE_PKCODE")));
        if (null == viewList || viewList.size() == 0) {
            return true;
        } else {
            StringBuffer eroor = new StringBuffer();
            for (DynaBean view : viewList) {
                String ybbm = view.getStr("VIEWCASCADE_YBBM");
                String mbbbm = view.getStr("VIEWCASCADE_MBBBM");
                eroor.append((MessageUtils.getMessage("table.id.tableCode", ybbm, mbbbm) + "\n"));
            }
            throw new APIWarnException(MessageUtils.getMessage("table.id.update.view", eroor.toString()), "201", new Object[]{dynaBean});
        }
    }

    /**
     * 生成修改主键名所生成的ddl
     *
     * @param oldPk
     * @param newPK
     * @return
     */
    @Override
    public List<String> generateChangeTablePrimaryKeyDDL(String tableCode, String oldPk, String newPK) {
        DynaBean dynaBean = metaService.selectOne("JE_CORE_TABLECOLUMN",
                ConditionsWrapper.builder().eq("TABLECOLUMN_TABLECODE",tableCode).eq("TABLECOLUMN_TYPE","ID"));
        List<String> ddlList = new ArrayList<>(2);
        boolean isColumnOfCurrentTable =   changePrimaryKeyService.checkNewPrimaryKeyIsExistsOfCurrentTable(tableCode,newPK);
        if(isColumnOfCurrentTable){
            if(dynaBean!=null){
                //如果表的主键存在
                String dropDdl = "ALTER TABLE " + tableCode + " DROP PRIMARY KEY;";
                ddlList.add(dropDdl);
            }

        }else{
            String addDdl = "ALTER TABLE " + tableCode + " ADD " + newPK + " VARCHAR(50) NOT NULL;";
            ddlList.add(addDdl);
            if(dynaBean!=null){
                //先删除原字段，再将新字段设置为主键
                String changeDdl = "ALTER TABLE " + tableCode + " DROP COLUMN " + oldPk + "";
                ddlList.add(changeDdl);
            }
        }
        String primaryDDL = BuildingSqlFactory.build().getDDL4AddPrimary(tableCode,newPK);
        ddlList.add(primaryDDL);
        return ddlList;
    }

    /**
     * 在资源表中根据id查询表信息
     *
     * @param resourceTable
     * @param resourceId
     * @return
     */
    @Override
    public DynaBean selectOneByPk(String resourceTable, String resourceId) {
        DynaBean dynaBean = metaService.selectOneByPk(resourceTable, resourceId);
        return dynaBean;
    }

    /**
     * 根据表编码和指定类型获取表信息
     *
     * @param tableCode
     * @return
     */
    @Override
    public DynaBean selectOneByCodeToType(String tableCode) {
        DynaBean table = metaService.selectOne("JE_CORE_RESOURCETABLE", ConditionsWrapper.builder().ne("RESOURCETABLE_TYPE", "MODULE")
                .eq("RESOURCETABLE_TABLECODE", tableCode));
        return table;
    }

    /**
     * 根据资源表id查询实体表信息
     *
     * @param tableCode
     * @param resourcetableId
     * @return
     */
    @Override
    public List<DynaBean> selectTableByResourceTablePk(String tableCode, String resourcetableId) {
        List<DynaBean> columnss = metaService.select(tableCode,
                ConditionsWrapper.builder().eq("TABLECOLUMN_RESOURCETABLE_ID", resourcetableId));
        return columnss;
    }

    /**
     * 根据资源表id查询实体表信息
     *
     * @param tableCode
     * @param tablecolumnId
     * @param ids
     * @return
     */
    @Override
    public List<DynaBean> selectTableInIds(String tableCode, String tablecolumnId, String[] ids) {
        List<DynaBean> columList = metaService.select(ConditionsWrapper.builder().table(tableCode).in(tablecolumnId, ids));
        return columList;
    }

    /**
     * 据资源表id查询实体表信
     *
     * @param ids
     * @return
     */
    @Override
    public List<DynaBean> selectColmListInIds(String ids) {
        List<DynaBean> columns = metaService.select(ConditionsWrapper.builder().table("JE_CORE_TABLECOLUMN").in("JE_CORE_TABLECOLUMN_ID", ids.split(ArrayUtils.SPLIT)));
        return columns;
    }

    /**
     * 修改时校验编码唯一性
     *
     * @param dynaBean
     * @return
     */
    @Override
    public Boolean checkTableCodeExcludeCode(DynaBean dynaBean) {
        String resourcetableTablecode = dynaBean.getStr("RESOURCETABLE_TABLECODE");
        int count = 0;
        if (Strings.isNullOrEmpty(dynaBean.getStr("JE_CORE_RESOURCETABLE_ID"))) {
            count = metaService.select("JE_CORE_RESOURCETABLE", ConditionsWrapper.builder().eq("RESOURCETABLE_TABLECODE", resourcetableTablecode)).size();
        } else {
            count = metaService.select("JE_CORE_RESOURCETABLE", ConditionsWrapper.builder().eq("RESOURCETABLE_TABLECODE", resourcetableTablecode)
                    .ne("JE_CORE_RESOURCETABLE_ID", dynaBean.getStr("JE_CORE_RESOURCETABLE_ID"))).size();
        }
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public File exportExcel(String ids, String fileName) {
        List<DynaBean> beanList = metaService.select("JE_CORE_RESOURCETABLE",ConditionsWrapper.builder().in("JE_CORE_RESOURCETABLE_ID", Splitter.on(",").splitToList(ids)));
        String defaultDirectory = environment.getProperty("servicecomb.downloads.directory");
        for (DynaBean table : beanList) {
            developLogService.doDevelopLog("EXPORT_EXCEL", "导出Excel", "TABLE", "资源表", table.getStr("RESOURCETABLE_TABLENAME"), table.getStr("RESOURCETABLE_TABLECODE"), table.getStr("JE_CORE_RESOURCETABLE_ID"),table.getStr("SY_PRODUCT_ID"));
        }
        InputStream inputStream = null;
        FileUtil.writeFromStream(inputStream, defaultDirectory + File.separator + fileName);
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return new File(defaultDirectory + File.separator + fileName);
    }

    /**
     * 查询每个功能主子
     *
     * @param tableByFuncList
     * @return
     */
    private List<TableDataView> selectFuncRelation(List<TableDataView> tableByFuncList) {
        for (TableDataView func : tableByFuncList) {
            List<Map<String, Object>> list = metaService.selectSql("SELECT FUNCRELATION_FUNCINFO_ID FROM JE_CORE_FUNCRELATION WHERE FUNCRELATION_CODE={0}", func.getTableCode());
            if (null != list && 0 < list.size()) {
                func.setTableType("slave");
            } else {
                func.setTableType("master");
            }
        }
        return tableByFuncList;
    }

    /**
     * 拼接INSERT SQL
     *
     * @param columnName
     * @param columnValue
     * @param tableCode
     * @return
     */
    private String insertSQL(StringBuffer columnName, StringBuffer columnValue, String tableCode) {
        StringBuffer insertSQL = new StringBuffer();
        insertSQL.append(insert)
                .append(" ")
                .append(tableCode)
                .append("(")
                .append(columnName.toString())
                .append(")")
                .append(values)
                .append("(")
                .append(columnValue.toString())
                .append(");");
        return insertSQL.toString();
    }


    private StringBuilder getOrderDdl(JSONArray orderList) {
        StringBuilder sql = new StringBuilder("");
        for (int i = 0, size = orderList.size(); i < size; i++) {
            String column = orderList.getString(i);
            if (StringUtil.isEmpty(column)) {
                continue;
            }
            if (i == 0) {
                sql.append(" ORDER BY ");
            }
            sql.append(column);
            if (size - 1 != i) {
                sql.append(",");
            }
        }
        return sql;
    }

    private StringBuilder getWhereDdl(JSONArray whereList) {
        StringBuilder sql = new StringBuilder("");
        for (int i = 0, size = whereList.size(); i < size; i++) {
            String column = whereList.getString(i);
            if (StringUtil.isEmpty(column)) {
                continue;
            }
            if (i == 0) {
                sql.append(" WHERE ");
            }
            sql.append(column);
            if (size - 1 != i) {
                sql.append(" AND ");
            }
        }
        return sql;
    }

    private StringBuilder getColumnDdl(JSONArray columnList, String tableCode) {
        List<DynaBean> columns = metaService.select("JE_CORE_TABLECOLUMN",
                ConditionsWrapper.builder().eq("TABLECOLUMN_TABLECODE", tableCode));
        String primaryCode = tableCode + "_ID";
        for (DynaBean column : columns) {
            if ("ID".equals(column.getStr("TABLECOLUMN_TYPE"))) {
                primaryCode = column.getStr("TABLECOLUMN_CODE");
            }
        }
        boolean containsPrimary = !columnList.contains(primaryCode);
        StringBuilder sql = new StringBuilder("");
        if (columnList.isEmpty()) {
            sql.append(" * ");
            return sql;
        }
        for (int i = 0, size = columnList.size(); i < size; i++) {
            String column = columnList.getString(i);
            if (StringUtil.isEmpty(column)) {
                continue;
            }
            sql.append(column);
            if (size - 1 != i) {
                sql.append(",");
            }
        }
        if (containsPrimary) {
            sql.append("," + primaryCode);
        }
        return sql;
    }


}
